Compare commits

..
223 Commits
Author SHA1 Message Date
Gina Häußge 97d37c5078 Merge branch 'master' into rc/maintenance 2018-07-25 16:28:28 +02:00
Gina Häußge 432090a56a Preparing release of 1.3.9 (part 2) 2018-07-25 16:27:05 +02:00
Gina Häußge 1847b41f7e Preparing release of 1.3.9 2018-07-25 13:38:57 +02:00
Gina Häußge 92c43ee6f9 docs: slight adjustment in wording 2018-07-23 09:48:41 +02:00
Iván cce37f0501 Remove malicious link as noticed in #2746 2018-07-23 09:45:53 +02:00
Gina Häußge 71b2cc87a3 Preparing release of 1.3.9rc4 2018-07-20 11:14:48 +02:00
Gina Häußge 2062acd372 Fix print button being enabled w/o selected file
Closes #2737
2018-07-18 17:21:20 +02:00
Gina Häußge fe13348fd3 Don't perform write tests on every getBaseFolder call
Especially not when rendering the main UI - we don't want to trigger
a 500 then, even if some folders are misconfigured.
2018-07-18 15:41:26 +02:00
Gina Häußge 903dd36d68 Strip --no-cache-dir for pip < 1.6
Closes #2738
2018-07-18 11:08:47 +02:00
Gina Häußge 460481c9c2 staging/maintenance is now 1.3.9rc4.dev 2018-07-16 15:21:25 +02:00
Gina Häußge 2806676707 Preparing release of 1.3.9rc3 2018-07-16 13:15:00 +02:00
Gina Häußge 0a634a76a0 Different fix for #2632
Our original one causes dead locks as reported in #2677
2018-07-12 16:46:28 +02:00
Gina Häußge 41c0dac19d Fix state comparisons in timeout handling
We weren't yet looking at the new intermediary states here.
2018-07-12 14:40:57 +02:00
Gina Häußge f728423f29 Fix resend handling during job_on_hold
Missing response to a resent line was not properly detected and handled.
2018-07-12 14:39:45 +02:00
Gina Häußge 61e5184377 Fix "now" timestamp
Should be taken *after* reading from the serial line, not before.
2018-07-12 14:38:12 +02:00
Gina Häußge a2527998c2 Resolve dead lock issue in job_on_hold implementation
(Hopefully) closes #2677
2018-07-11 18:10:51 +02:00
Gina Häußge 386ae7609d Fix initialization order of estimator
Closes #2719
2018-07-06 16:55:05 +02:00
Gina Häußge e15946ff79 staging/maintenance is now 1.3.9rc3.dev 2018-07-06 14:34:19 +02:00
Gina Häußge fd94fc94a0 Merge branch 'staging/maintenance' into rc/maintenance 2018-07-06 13:01:31 +02:00
Gina Häußge 798bc2b225 Preparing release of 1.3.9rc2 2018-07-06 13:01:19 +02:00
Gina Häußge 6728302bb3 Preparing release of 1.3.9rc2 2018-07-06 12:55:25 +02:00
Gina Häußge f7a3e6a6ee Add --no-cache-dir flag to update pip operations
Otherwise we might run into some weird infinite loop issues within
pip's cache handling under certain circumstances, and we really
don't want to risk that in the field.

See also #2543 for another issue worked around by this, and
pypa/pip#3532 for the core issue
2018-07-06 12:08:52 +02:00
Gina Häußge 0834288cfc Fix estimator initialization on SD print start
Closes #2715
2018-07-05 10:59:14 +02:00
Gina Häußge faff20943f Capture & log any errors in the state update worker
See #2715
2018-07-05 10:58:45 +02:00
Gina Häußge a97b8c2fd9 Sanity check disabled plugin list just in case
See https://github.com/foosel/OctoPrint/issues/2687#issuecomment-399797596
2018-06-25 11:20:31 +02:00
Gina Häußge 887304fe18 Some more badges 2018-06-20 23:01:23 +02:00
Gina Häußge 2bd8aa00f3 Add build status and IRC badge 2018-06-20 20:03:19 +02:00
Gina Häußge e49a4d8cfa staging/maintenance is now 1.3.9rc2.dev 2018-06-20 15:52:00 +02:00
Gina Häußge fdf0f75ffa Preparing release of 1.3.9rc1 (part 2) 2018-06-20 15:18:42 +02:00
Gina Häußge 5fb8674937 Merge branch 'master' into maintenance 2018-06-20 13:08:25 +02:00
Gina Häußge d3871e3487 Pin sarge to 0.1.4
0.1.5 renamed the async keyword.

Library authors, please, stick to semantic versioning :(
2018-06-20 12:48:10 +02:00
Gina Häußge 9dd9badb33 Pin tornado to 4.5.3
We don't want to accidentally pull in 5.0b1
2018-06-19 18:49:41 +02:00
Gina Häußge 3de9635180 Preparing release of 1.3.9rc1 2018-06-19 18:48:28 +02:00
Gina Häußge e2f626d421 Virtual printer: select_sd command 2018-06-19 11:24:05 +02:00
Gina Häußge b7a8c29fb4 Add an API endpoint to fetch template order
That should make it easier for third party plugins that want to offer
reordering capabilities of tab, sidebar, etc
2018-06-18 19:35:47 +02:00
Gina Häußge 15f10d4a84 sidebar > tabs 2018-06-18 18:23:03 +02:00
Gina Häußge 0faf2792e9 Clarify something about component ordering 2018-06-18 18:21:59 +02:00
Andy Castille caa1a3d76f Display absolute file upload times on hover 2018-06-18 18:03:01 +02:00
Gina Häußge fae01d2c75 Merge branch 'pr/2633' into maintenance 2018-06-18 17:53:47 +02:00
Gina Häußge 248235c5e0 Fix indentation 2018-06-18 17:53:32 +02:00
Gina Häußge 2febfcd8b3 Announcements: Don't reload on mark read
Only reload if we mark read from the management dialog.
2018-06-18 16:05:10 +02:00
Gina Häußge 704331525f Split settings init to allow better error logging 2018-06-18 15:37:51 +02:00
Gina Häußge 6c279f155a Improve fatal startup error handling 2018-06-18 15:07:18 +02:00
Gina Häußge e5afde2c2c Up a couple of versions 2018-06-18 14:33:28 +02:00
Gina Häußge f5b99a6e34 Fix symlink test util
That was resolving the path completely before checking
whether the symlink is broken or not.
2018-06-18 14:24:04 +02:00
Gina Häußge 8ef13ba529 Fix flask version 2018-06-18 14:22:56 +02:00
Gina Häußge 654055da61 Add symlink check to test API endpoint 2018-06-18 11:37:36 +02:00
Gina Häußge 68f67219ed Refactor test API endpoint 2018-06-18 11:37:02 +02:00
Gina Häußge 436ffb6db8 Detect broken symlinks during folder validation
Closes #2644
2018-06-18 11:20:21 +02:00
Gina Häußge b569cc456b Fix typePath missing for sdcard files on files API
Closes #2589
2018-06-18 10:48:27 +02:00
dadosch 023b9eda90 Two spaces were missing 2018-06-18 09:54:33 +02:00
Gina Häußge fe2dbf699d SWU: Lock down UI while updating
Implements #1217
2018-06-15 18:15:13 +02:00
Gina Häußge 17c6c83503 Fix SD printing 2018-06-15 17:02:53 +02:00
Gina Häußge 688e4d36d1 Fix script order
beforePrint* should always precede any commands from the print job.

Also make sure we only jump from "finishing" to "operational" after the
afterPrintDone script has been sent. Also wait for all moves to finish.
2018-06-15 15:44:34 +02:00
Gina Häußge 86b886ede7 Remove resend repetition code
It's apparently completely broken and the fact that no one noticed
and reported that means it never really gets used either from the looks
of it.

So instead of allowing it to introduce broken resend handling, we'll
rather remove it for now.
2018-06-15 13:15:27 +02:00
Gina Häußge 392149b504 Add view model list to coreui object 2018-06-14 19:25:46 +02:00
Gina Häußge 85ef3f1df2 Fix modals not hiding fully anymore 2018-06-09 13:07:34 +02:00
Gina Häußge 6e44149284 Treat scripts triggered by job as part of the job
Including blocking their sending via job_on_hold.

Closes #2583
2018-06-09 11:58:53 +02:00
Gina Häußge 534f3aa2d4 Fix for potential division by zero on SD upload
Closes #2675
2018-06-09 10:15:56 +02:00
Gina Häußge 13e5cf45ec Fix reset handling while printing
Could get stuck in cancelling due to resend issues.

Should fix #2509
2018-06-08 17:14:40 +02:00
Gina Häußge 4cb103e042 Fix cancel_preparation call in case of failure
It should be _failed if the timer runs out, not _done. Only difference
is a log entry though, so not that big of a deal.
2018-06-08 11:03:44 +02:00
Gina Häußge db81bf1e72 Add new states "resuming" and "finishing"
The later allows us to distinguish between a file having been streamed
completely and the print job done script having streamed completely as
well.

Should fix #2547
2018-06-05 11:07:31 +02:00
Gina Häußge 9c89c4c999 Simplified a log handler 2018-06-04 18:44:10 +02:00
Gina Häußge d133bd47e5 Fix uninstall detection of disabled plugins
Fixes #2549 part 2
2018-06-04 18:01:34 +02:00
Gina Häußge 90391d2897 Forbid <=0 for various timeouts & intervals
Closes #2551
2018-06-04 15:13:45 +02:00
Gina Häußge d124efdb71 Fix race condition in resend handling
Could be triggered if two resend requests without an ok were directly
following each other, causing a resend ok timer to be triggered for each
and a consequent attempt to process the same resend status again.

Should fix #2632
2018-05-29 17:30:59 +02:00
Gina Häußge 4f1b781219 docs: forgot to push two images 2018-05-29 16:13:50 +02:00
Gina Häußge 6673536e10 Added some additional printer safety checks
* Repetier firmware versions prior to 0.92 don't have thermal runaway/
    decouple detection, so we always warn about those
  * If the firmware supports the THERMAL_PROTECTION capability report
    but it's reported as disabled, we also warn about that (see also
    MarlinFirmware/Marlin#10465)
2018-05-29 15:19:35 +02:00
Gina Häußge 118afd4720 Refactor version parsing helpers
Extract get_comparable_version for use in other places as well.
2018-05-29 15:16:14 +02:00
Gina Häußge a0cbc10ba7 Add two new hooks for firmware information
octoprint.comm.firmware.info - response to M115
octoprint.comm.firmware.capabilities - capability report lines
2018-05-29 15:13:25 +02:00
Gina Häußge 38b7640769 Add support for prompt_* action commands 2018-05-28 18:16:06 +02:00
Gina Häußge b266f1ca55 Update psutil dependency
Might fix #2658 (although I'm still at a complete loss as to how that
lib could influence serial connection stability O_O).
2018-05-28 10:46:40 +02:00
Gina Häußge 0ef0eff917 Add paused and resumed action commands
Slightly different behaviour than the already existing pause and resume,
see the docs.
2018-05-25 18:21:11 +02:00
Gina Häußge fd29efe88e Update jQuery to 3.3.1 2018-05-25 17:25:58 +02:00
Gina Häußge cd3acfb384 Merge branch 'pr/2606' into maintenance 2018-05-25 16:49:33 +02:00
Gina Häußge f9548a7ece Sort serial ports naturally 2018-05-25 16:42:46 +02:00
Gina Häußge ce5275c91e docs: Add example for float factors
Closes #2663
2018-05-25 14:57:35 +02:00
Gina Häußge 8a1db8e4c5 Disable fade in for cancel confirmation
Requests to add an option for it in 3, 2, 1...

Closes #2597
2018-05-18 18:22:19 +02:00
Gina Häußge 0d120b2977 Merge pull request #2650 from ntoff/fix/grey-plugin-delete-clickable
Fix greyed plugin manager delete icons still being clickable
2018-05-18 12:42:00 +02:00
ntoff bf71a20ac1 Fix greyed plugin manager delete icons still being clickable
Fixes https://github.com/foosel/OctoPrint/issues/2549
2018-05-18 19:21:50 +10:00
Gina Häußge 846d3a63bc Merge pull request #2648 from malnvenshorn/class-methods-as-callbacks
Allow class methods as callbacks in view model
2018-05-18 10:00:48 +02:00
malnvenshorn 15d6bf3a70 Allow class methods as callbacks in view model 2018-05-17 19:11:52 +02:00
Gina Häußge cec1bc6c0f Allow plugins to override analysis & print time estimation
Using two new hooks, plugins may now provide alternative implementations
for the GCODE analysis and the live print time estimation.

Should allow people to get creative with regards to #1203, #1905, #2281,
#2445, #2514

Implements #1797, #1905
2018-05-17 18:58:15 +02:00
Gina Häußge 5456f5a70a Fix potential for invalid sorting of uploads
"date" and "size" might be undefined on both parameters (e.g. for
folders, SD files). We have no guarantee that "a" will always have
either defined, so make sure to test or a wrong sorting order might be
the consequence.

Fixes #2355
2018-05-17 10:57:01 +02:00
Gina Häußge e980444f86 Merge pull request #2642 from malnvenshorn/itemlisthelper-add-update
ItemListHelper - Methods for adding and updating items
2018-05-15 17:14:37 +02:00
malnvenshorn 9d1f4fb126 Add methods for adding and updating items 2018-05-14 13:52:03 +02:00
sylvled 3de5bca48b Update config_yaml.rst
gcodeAnalysis and gcodeViewer were without section name. Added them.
2018-05-07 10:28:14 +02:00
Gina Häußge 81471df419 Option to send M0/M1 to the printer
Also added a message to the serial output if M0/M1 is blocked.

Closes #1513
2018-05-05 15:49:59 +02:00
Gina Häußge 99ef84788a SWU: Support updating single items via UI
Closes #2615
2018-05-05 15:13:25 +02:00
Gina Häußge bfbf9fb66e Confirmation dialog helper now supports an html body 2018-05-05 15:12:03 +02:00
Gina Häußge 6074a3d964 Never send referrers with links 2018-05-05 14:01:29 +02:00
Gina Häußge 74e82afa24 About: Use github logo for source link 2018-05-05 13:50:27 +02:00
Gina Häußge 2b5c14b3c3 Change "Cancel" to "Close" on Settings
The Settings dialog also allows some "instant actions" (e.g. adding
users, changing specific plugin settings and so on). Having to click on
"Cancel" after actually doing something just feels wrong in such cases
so the Settings dialog now has a "Close" instead of a "Cancel" button.

Other sub dialogs will stay as is since that better reflects their
behaviour.
2018-05-05 13:48:19 +02:00
Gina Häußge e5b167bcb4 Merge branch 'pr/2595' into maintenance 2018-05-05 13:29:33 +02:00
Gina Häußge a70928aac6 Revert "Fix trivial copy and paste errors"
This reverts commit e02679a

It actually wasn't a copy and paste error - it *is* a plugin after all,
so "PluginSettings" makes sense.
2018-05-05 13:29:11 +02:00
Gina Häußge 7548e7a623 Revert "Replace "Cancel" label with "Abort" on buttons for consistency"
This reverts commit eb37607
2018-05-05 13:28:04 +02:00
Gina Häußge 8d9034b5a4 Gcode viewer: show approx. print head position
Also change retract/resume from dot to triangle/inverted triangle.

Closes #2318
2018-05-05 12:56:12 +02:00
Gina Häußge b5194ffc00 Plugin core: Fetch package name from entry point
See also #2625
2018-05-05 12:56:12 +02:00
Gina Häußge fa6cda3356 Merge pull request #2620 from malnvenshorn/itemlisthelper-save-pagesize
ItemListHelper - Save page size to local storage
2018-05-05 10:14:25 +02:00
Ben Lye 4d9ec9a7e3 Add M118 to commands to not uppercase
Adds M118 to the default list of commands which should not automatically be converted to uppercase.
2018-05-05 10:10:02 +02:00
Gina Häußge e44a2fdd97 Update pkginfo dependency 2018-05-04 12:55:32 +02:00
Gina Häußge 95ac669d5c Plugin subsystem: Use entry_point.dist to fetch metadata
Support egg "PKG-INFO" and wheel "METADATA" files in metadata folder. Less
guess work throughout the include path this way.

Better solution for #2625 than c3eebdb
2018-05-04 12:55:16 +02:00
Gina Häußge 5e899204f0 Merge branch 'hotfix/pip10' into maintenance 2018-05-03 18:02:14 +02:00
Gina Häußge c3eebdb158 Fix plugin metadata parsing for pip 10+ 2018-05-03 18:00:28 +02:00
Gina Häußge 13b85fbbd0 Fix fps source when rendering unrendered timelapse
Should be taken from config unless provided as parameter, not hard coded
to 25.

Closes #2621
2018-05-03 15:40:36 +02:00
Gina Häußge ddd2711f95 Fix a broken unit test
We now initialize the folders when initializing the settings, so the
test that the folder didn't yet exist before retrieving its path
naturally failed.
2018-05-03 12:18:10 +02:00
Gina Häußge 9addbbb9a1 Fix refactoring bug
Closes #2617
2018-05-03 11:45:46 +02:00
malnvenshorn 735e2c6c94 Convert page size to integer when reading from local storage 2018-05-01 15:50:27 +02:00
malnvenshorn 9d2ee2b55b Save page size to local storage 2018-05-01 12:32:55 +02:00
malnvenshorn 7988e7487f DRY principle for storage IDs 2018-05-01 12:21:01 +02:00
Gina Häußge 4bbe49ac6d Sanity check for configured folders
* On startup: Check they are writable, if not revert to defaults
  * On settings save: Check they are writable, if not return an HTTP 400
  * In the settings dialog: Allow quick check of writability via Test
    buttons

Should hopefully prevent users from nuking their instance by configuring
some custom folder that isn't writable.

TODO:
Currently simply doesn't close the settings dialog, needs some message
or something (or client side folder validation on clicking the button).
2018-04-27 17:44:07 +02:00
Gina Häußge 9e32439f44 Watchdog: Ignore hidden & removed files
Closes #2558
2018-04-27 16:17:04 +02:00
Gina Häußge 3ebb36f877 Disable user display if access control is disabled
Also show something more human friendly if the active user for a print
job is the "_api" user of the global api key.
2018-04-27 11:53:49 +02:00
Gina Häußge b2996f10ff Get rid of a bit of Python2 only code 2018-04-26 12:56:07 +02:00
Gina Häußge 42fb4f4700 Fix remember me and IPv4/IPv6 sessions
Session protection mode "strong" is apparently incompatible to the
remember me function in general and on top of that I observed issues
with at least Windows happily switching between connecting to an
instance via IPv4 and IPv6, causing changes in the reported client IP
and hence the session protection killing the session as a result.
2018-04-26 12:40:07 +02:00
Gina Häußge 52934602cd Fix forgotten self 2018-04-26 12:03:34 +02:00
Gina Häußge 2a0eda5c34 Make sure we have the current user data in editor
Fixes #2534
2018-04-26 11:30:48 +02:00
Gina Häußge a3b3fbe269 Add some more strings to the known error classes
"Missing linenumber" is apparently also an option we want to recognize
as non critical error, and while we are at it let's make sure we also
capture "linenumber" without a space for resend request communication
errors, just in case firmware devs add some variance here.
2018-04-26 11:00:29 +02:00
Gina Häußge 2fe177ffb8 Virtual: Fix default M114 format string 2018-04-25 17:01:24 +02:00
Gina Häußge d8bc75222f Remove some left overs from a small refactor
Closes #2610
2018-04-25 17:01:24 +02:00
Gina Häußge c3bb651d9e Properly decouple individual metadata locks
Thanks to @CapnBry for the heads-up here.
2018-04-25 17:01:24 +02:00
Gina Häußge 135cf6a9cc Migrate file storage metadata to json
As suggested by @CapnBry, that should give us a significant speed
boost considering that yaml serialization and deserialization is some
orders of magnitude slower than json.

We only do that for the file metadata for now - it has the biggest gain
to expect from a speed boost, and having the configuration as yaml
actually has its readability advantages.
2018-04-25 17:01:24 +02:00
Gina Häußge be4b98b9da Merge pull request #2604 from dforsi/fix/issue/2534
Reload older values after cancelling the Settings dialog
2018-04-25 10:51:41 +02:00
Gina Häußge 673b367902 Merge pull request #2591 from dforsi/fix/valid-html
Fix markup for some HTML labels
2018-04-25 10:41:57 +02:00
Gina Häußge 81626ceec5 Small change in user display in state panel 2018-04-24 16:52:17 +02:00
Gina Häußge b653ee59c8 Merge branch 'pr/2576' into maintenance
# Conflicts:
#	src/octoprint/printer/standard.py
2018-04-24 16:45:08 +02:00
Gina Häußge 79abe31a06 Move printing user into job data & add UI representation 2018-04-24 16:44:41 +02:00
Gina Häußge 30a523b8c1 Fix printer.select_file
* properly handle relative paths for selection
  * properly handle absolute paths for recovery data comparison

Fixes #2601
2018-04-24 16:00:09 +02:00
Gina Häußge c104f45b16 SWU: Default to force_base = False 2018-04-24 13:49:21 +02:00
Gina Häußge a9bc814016 Merge branch 'master' into maintenance 2018-04-24 13:18:47 +02:00
Gina Häußge edd00cfa80 Some adjustments for PyPI stuff 2018-04-24 12:41:45 +02:00
Daniele Forsi 60baf54d7b Refresh the details in the Connection pane when settings are updated 2018-04-23 23:54:02 +02:00
Daniele Forsi 536f5458bb Show details in the Connection pane ordered as in the Settings dialog
Return the Serial Port and the Baudrate lists without sorting them.
2018-04-23 16:05:47 +02:00
Daniele Forsi a4cc3a9309 Reload older values after cancelling the Settings dialog
Fixes #2534
2018-04-22 23:09:37 +02:00
Gina Häußge f72b92caff Revert Tornado 5 fixes for sockjs 2018-04-20 22:39:26 +02:00
Gina Häußge d3e7842c3a Revert "Minor adjustments for Tornado 5"
This reverts commit 258f3725bf.
2018-04-20 22:39:25 +02:00
Gina Häußge 555bdefd46 Pin tornado to >=4.5.3,<5 for now
There appears to be a memory leak issue with tornado 5.x as reported in #2585
2018-04-20 22:39:20 +02:00
Daniele Forsi 206c22f6aa Add some icons to the About page
Also moves Documentation so that the first 4 items are the same as in the footer.
2018-04-19 18:34:40 +02:00
Daniele Forsi 14959c2d66 Hide the buttons when the file list is hidden 2018-04-19 17:51:00 +02:00
Daniele Forsi eb3760715f Replace "Cancel" label with "Abort" on buttons for consistency
Now only the main settings dialog has a "Cancel" button and the other
dialogs have "Abort" on the buttons that do not save the changes.
2018-04-19 15:55:35 +02:00
Daniele Forsi e02679a587 Fix trivial copy and paste errors 2018-04-19 15:36:09 +02:00
Daniele Forsi 4064b3fc72 Make the API buttons and title in the Settings similar to those in other dialogs 2018-04-19 15:36:09 +02:00
Daniele Forsi e3f2a16e92 Fix caret icon always shown in position "closed" even whe details are visible 2018-04-19 15:36:09 +02:00
Gina Häußge a9441400b3 Merge branch 'fix/positionLogTimeout' into maintenance
# Conflicts:
#	src/octoprint/util/comm.py
2018-04-19 14:10:16 +02:00
Gina Häußge 09781613ce Add timeout for position log on pause/cancel
Workaround for firmware which doesn't provide a proper M114 report that might
be unparseable. We don't want to get stuck in such cases (which appear to be more
common than should be the case - this whole comm situation is just FUBAR).
2018-04-19 14:09:18 +02:00
Gina Häußge 63b63f6aad Test for image/* in snapshot test 2018-04-19 13:10:58 +02:00
Gina Häußge 1637187c76 Extend URL test to also allow whitelist/blacklist check for the returned content type 2018-04-19 13:10:41 +02:00
Gina Häußge 303ef405bb Fix snapshot test button not resetting on error 2018-04-19 13:01:37 +02:00
Gina Häußge bf3da2a662 Fixes a race condition causing stalls when pausing/cancelling
Closes #2581 & closes #2587
2018-04-18 13:02:36 +02:00
Gina Häußge b8194ecc84 Fixes a race condition causing stalls when pausing/cancelling
Closes #2581
2018-04-18 12:59:38 +02:00
Gina Häußge 472ab367b0 Disable logging the position on cancel by default
Apparently that is causing too many issues in the field. If someone
actually DOES need the position data, they can always enable this.
2018-04-18 12:59:38 +02:00
Gina Häußge 8f50180543 Virtual: allow defining custom M114 responses 2018-04-17 09:10:33 +02:00
Daniele Forsi 11eae082fc Remove invalid xmlns attributes so that the default value is used
Fixes 2 validation errors:
Error: Bad value http://www.w3.org/1999/html for the attribute xmlns (only http://www.w3.org/1999/xhtml permitted here).
          <div id="offline_overlay" xmlns="http://www.w3.org/1999/html">↩    <
Error: Bad value http://www.w3.org/1999/html for the attribute xmlns (only http://www.w3.org/1999/xhtml permitted here).
          <div id="reloadui_overlay" xmlns="http://www.w3.org/1999/html">↩    <
2018-04-16 20:07:28 +02:00
Daniele Forsi 885446328d Add missing "for" and "id" attributes to some HTML labels 2018-04-16 20:07:28 +02:00
Daniele Forsi 8cb4d84905 Fix HTML labels with wrong "for" attribute
Fixes some validation errors detected by https://validator.w3.org and other errors.
2018-04-16 20:07:28 +02:00
Gina Häußge 0da52cb366 Update pyserial to 3.4
Final part of the fix for #2333
2018-04-13 18:32:09 +02:00
Gina Häußge 57ea18a9a4 Fix Print Job Left display
Fixes #2579
2018-04-13 18:17:03 +02:00
Gina Häußge 06478415b5 Merge remote-tracking branch 'refs/remotes/origin/maintenance' into maintenance 2018-04-13 17:08:47 +02:00
Gina Häußge 6a8a1c31e3 maintenance is now 1.3.9.dev 2018-04-13 17:08:19 +02:00
Gina Häußge cce7961ee3 Merge branch 'staging/maintenance' into maintenance 2018-04-13 17:07:48 +02:00
Gina Häußge 725227338a Merge branch 'rc/maintenance' into staging/maintenance 2018-04-13 17:06:36 +02:00
malnvenshorn b41df46491 Added @malnvenshorn to AUTHORS.md 2018-04-12 17:00:37 +02:00
malnvenshorn 5205d2e352 Tracking user of print job 2018-04-12 16:15:53 +02:00
Gina Häußge 9c923be5f0 Better solution for the Tornado 5 + SockJS + haproxy issue
Looks like Nagle's algorithm was the cause. Adding

    option http-no-delay

to haproxy.cfg solves the problem without modification of the timeout,
however that is not an option for the thousands of instances already
deployed in the field.

So instead we add 300ms to the roundtrip based connection timeout, that
should hopefully get around any Nagle-induced delays (usually between
40 and 200ms according to various sites on the net).
2018-04-12 13:19:02 +02:00
Gina Häußge 88328bbe0e Merge pull request #2568 from vitormhenrique/master
Fix dead link on hooks documentation
2018-04-12 12:58:46 +02:00
Gina Häußge 132614045c Early detection & logging of broken files response
Fixes #2572
2018-04-12 12:08:19 +02:00
Gina Häußge a33b037364 Fix ItemListHelper throwing an error on undefined items
Just fall back to an empty list.

Fixed #2572 (at least the bit that isn't a broken nginx config)
2018-04-12 11:55:14 +02:00
Gina Häußge 33b27e450f Merge branch 'fix/sockjs' into maintenance 2018-04-11 18:47:18 +02:00
Gina Häußge a5d541dafc Fix sockjs not working behind haproxy
For some reason the websocket connection runs into a timeout, the xhr
transport doesn't properly take over, and then stuff takes ages to
realign again.

Only happens under Tornado 5, doesn't happen under Tornado 4.5

Increasing the timeout for now instead of pinning to Tornado 4.5 in the
hopes that might still be figured out.

Incredibly weird though.
2018-04-11 18:47:08 +02:00
Gina Häußge 258f3725bf Minor adjustments for Tornado 5 2018-04-11 18:43:23 +02:00
Gina Häußge c4d8e344d1 Remove wrongly placed whitespace 2018-04-11 11:15:46 +02:00
Gina Häußge f3128a15d9 Safety Plugin: Add Malyan M200 & CR-10S
Malyan M200 identified by firmware name "Malyan" and model "M200".
Printer also known as Monoprice Select Mini, see also ID strings in
#2271.

CR-10S identified by "Author: (CR-10Slanguage)".
2018-04-11 11:15:18 +02:00
Gina Häußge 6f224bd825 Workaround for typo & whitespace in Malyan M115 responses
NAME. instead of NAME:, whitespace between key and value component.
2018-04-11 11:12:56 +02:00
Vitor de Miranda Henrique 58bbbc2ad9 Update hooks.rst
Fix Software Update plugin link, it was pointing to an old github page --> https://github.com/OctoPrint/OctoPrint-SoftwareUpdate
instead of the bundled plugin--> https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate
2018-04-10 16:19:55 -05:00
Gina Häußge 75de062b55 Safety Plugin: Add detection of Anycubic Mega
Identified by "Author: (Jolly, xxxxxxxx.CO.)" in startup messages.
2018-04-10 18:09:55 +02:00
Gina Häußge 85dfcbd156 Merge branch 'staging/maintenance' into maintenance 2018-04-09 17:03:15 +02:00
Gina Häußge a6cec7d2ef Merge branch 'rc/maintenance' into staging/maintenance 2018-04-09 17:02:51 +02:00
Gina Häußge 7e0b187cb8 Bundle sockjs-tornado dependency
It appears to be unmaintained at the moment, and the current version
is incompatible to Tornado 5.

Instead of monkey patching ad infinitum we instead bundle the dependency
in the new vendor sub package.
2018-04-06 18:38:06 +02:00
Gina Häußge 025f545ef7 Better requirement detection in octoprint_setuptools
Plus unit tests.
2018-04-06 14:59:11 +02:00
Gina Häußge 6af1afb546 Don't tab to "forget password" link 2018-04-06 14:59:11 +02:00
Gina Häußge 1dd1eb3768 Merge pull request #2554 from tedder/upstream_maintenance
docfix: make 'settings' proper yaml
2018-04-06 09:33:32 +02:00
tedder 77d126fc09 make 'settings' proper yaml
See PR #2530; I assumed it should go into 'devel' so it is right in new releases, but Gina asked for it to be done here.
2018-04-05 13:38:25 -07:00
Gina Häußge 4a3902c060 Merge pull request #2533 from dforsi/fix/fix-api-buttons
Fix buttons not disabled when there isn't an API key available
2018-04-05 12:59:08 +02:00
Gina Häußge 83cdd4d79d Merge pull request #2552 from dforsi/fix/fix-typos
Fix typos in the docs
2018-04-05 12:58:00 +02:00
Daniele Forsi 1d1191eae0 Fix typos in the docs 2018-04-04 23:13:32 +02:00
Daniele Forsi 1efa0fa1e6 Fix buttons not disabled when there isn't an API key available
Also keeps always enabled the button to refresh the global API key.
Bootstrap buttons made from HTML <a> tags can only be disabled with CSS.
2018-04-04 20:09:06 +02:00
Gina Häußge 085424f192 Support for binding to IPv6 addresses
Defaults to :: if IPv6 is supported, 0.0.0.0 otherwise. Both
intermediary server and Tornado are instructed to bind their sockets to
both IP versions.

Positive IPv6 support detection relies on

  * socket.has_ipv6 being True
  * socket.IPPROTO_IPV6 and socket.IPV6_V6ONLY being available (or
    redefined in case of Windows) in order to ensure dual stack binding
    for the intermediary server

Implements #2351
2018-04-04 15:04:33 +02:00
Gina Häußge db23bed00b Remove intermediary dialog for "forgot password"
Might annoy people after all having to click twice just to get the
information they are looking for.

Can be changed if the process gets changed.
2018-04-04 13:12:53 +02:00
Gina Häußge 9c31fa88a5 Merge branch 'staging/maintenance' into maintenance 2018-04-04 12:36:24 +02:00
Gina Häußge c5439da9d2 staging/maintenance is now 1.3.7rc5.dev 2018-04-04 12:34:57 +02:00
Gina Häußge 561bf83d88 Merge pull request #2540 from dforsi/fix/fix-rst
Add missing documentation for GCODE analysis and other small fixes
2018-04-04 09:51:06 +02:00
Gina Häußge baf8941f31 Merge pull request #2532 from dforsi/fix/fix-typos
Fix typo
2018-04-04 09:49:42 +02:00
Daniele Forsi f7dec5542b Fix typos 2018-04-03 23:41:34 +02:00
Daniele Forsi 6ec8b97ddb Add missing documentation for GCODE analysis and other small fixes
Adds documentation for `dimensions` and `printingArea`; fixes `length`
and `volume`; adds two internal references.
Fixes #2463.
2018-04-03 20:35:58 +02:00
Gina Häußge 35343705ca Merge pull request #2543 from ganey/bugfix/pip--no-cache-dir
Pip install with --no-cache-dir to handle plugin installations with MemoryError
2018-04-03 13:49:59 +02:00
Ganey 22e894c245 Merge branch 'maintenance' into bugfix/pip--no-cache-dir 2018-04-03 12:46:05 +01:00
Gina Häußge 4ef01610d0 Merge pull request #2541 from dforsi/dev/forgot-email
Add link to instructions to reset passwords
2018-04-03 13:34:29 +02:00
Michael Gane bb065828f2 pip install using --no-cache-dir for low memory devices 2018-04-03 10:51:52 +01:00
Daniele Forsi d0637f61d4 Add link to instructions to reset passwords 2018-04-02 23:46:06 +02:00
Daniele Forsi 84319366d1 Fix typo 2018-03-29 22:11:36 +02:00
Gina Häußge 2152c401bf Merge branch 'staging/maintenance' into maintenance 2018-03-29 16:59:24 +02:00
Gina Häußge 0070349d66 Fix browser session getting overwritten by API key
Closes #2505
2018-03-27 16:53:14 +02:00
Gina Häußge 0cbad44055 Fix temperature profiles saving string values
Closes #2520
2018-03-27 16:23:13 +02:00
Gina Häußge 2571d32134 Include children on first level folder listings
This allows step-by-step traversal of file listings without the
recursive flag.

Fixes #2496
2018-03-27 15:29:53 +02:00
Gina Häußge 64ee8bac60 Support parsing xheaders in tornado
That will give us more accurate client ips, with a one hop limitation
however, see http://www.tornadoweb.org/en/stable/httpserver.html. If
more than one hop/reverse proxy is used in front of OctoPrint, their IPs
should be configured as server.reverseProxy.trustedDownstream in
config.yaml so they don't get detected as client IPs.

Implements #2512
2018-03-27 14:54:52 +02:00
Gina Häußge da392b9c9f Log asynchronously
Implements #2522
2018-03-27 13:50:03 +02:00
Gina Häußge 3179a1846f Update to Tornado 5 2018-03-27 11:45:02 +02:00
Gina Häußge b3912b2281 Remove legacyPluginAssets flag 2018-03-26 15:33:33 +02:00
Gina Häußge db14723ea2 Use regular scrollbars instead of slimscroll
See #2379
2018-03-26 15:17:17 +02:00
Gina Häußge 28831a68dd Add (configurable) small delay before baudrate detection
Solves issue with controllers that don't like baudrate switches right
after connection, e.g. the Einsy board.

Fixes #2517
2018-03-26 14:43:56 +02:00
Gina Häußge 6f18495395 Merge branch 'staging/maintenance' into maintenance 2018-03-23 16:29:06 +01:00
Gina Häußge fc2ef8a09c Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2018-03-23 14:59:25 +01:00
Gina Häußge 0809540bd7 force always means "now", even when printing 2018-03-23 14:58:47 +01:00
Gina Häußge 3a71d39785 Merge pull request #2504 from dforsi/fix/fix-typos
Fix typos
2018-03-23 10:11:55 +01:00
Gina Häußge c41aecc2b8 Merge pull request #2502 from dforsi/fix/valid-html
Fix some invalid HTML
2018-03-23 10:11:21 +01:00
Daniele Forsi 06f62bd874 Fix a typo in the docs 2018-03-22 00:23:02 +01:00
Daniele Forsi 23bcbba013 Fix typo 2018-03-21 19:28:22 +01:00
Daniele Forsi cb18d3fe32 Fix some invalid HTML
Fixes 4 kinds of errors found with https://validator.w3.org/nu/#textarea
Bad value javascript for attribute lang on element script
Bad character after < . Probable cause: Unescaped < . Try
escaping it as &lt; .
The element label must not appear as a descendant of the label element.
Element legend not allowed as child of element form in this context.

Note: the change related to <legend> seems big because of the increased
indent of the existing code (use "git diff --ignore-all-space" or
"git log --patch --ignore-all-space" to see the lines actually added).
2018-03-21 16:14:02 +01:00
Gina Häußge 95694453f4 Merge pull request #2495 from dforsi/fix/remove-unneeded-format
Remove unneeded format() filter from template
2018-03-20 16:51:16 +01:00
Gina Häußge 0825e0660f Merge pull request #2498 from dforsi/fix/issue/2487
Document the async flag of custom system commands
2018-03-20 16:50:19 +01:00
Daniele Forsi 819d4d0fdf Expand the description of custom system commands
Fixes #2487
2018-03-20 16:12:49 +01:00
Daniele Forsi 1c43e193ba Remove unneeded format() filter 2018-03-19 18:55:14 +01:00
Gina Häußge 4f1cd6b3a2 maintenance is now 1.3.8.dev 2018-03-19 17:19:38 +01:00
160 changed files with 13952 additions and 5718 deletions

No files matched your search

+7 -7
View File
@@ -18,16 +18,16 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.7
# maintenance is currently the branch for preparation of maintenance release 1.3.9
# so are any fix/... and improve/... branches
maintenance 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
fix/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
improve/.* 1.3.7 99e1c3ac007a0eee9d6f908e598c6b029f3ae40c pep440-dev
maintenance 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
fix/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
improve/.* 1.3.9 da2c9632ea54fd1b3c8ae34f8f26bab29dbaf3c6 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.7rc4
# staging/maintenance is currently the branch for preparation of 1.3.9rc4
# so is regressionfix/...
staging/maintenance 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
regressionfix/.* 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
staging/maintenance 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
regressionfix/.* 1.3.9rc4 2806676707020b270097876d6189d3c484dd47b8 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.4.0-dev for now
.* 1.4.0 7f5d03d0549bcbd26f40e7e4a3297ea5204fb1cc pep440-dev
+4
View File
@@ -87,6 +87,10 @@ date of first contribution):
* [Josh Major](https://github.com/astateofblank)
* ["alex-gh"](https://github.com/alex-gh)
* [Bernd Zeimetz](https://github.com/bzed)
* [Daniele Forsi](https://github.com/dforsi)
* [Ganey](https://github.com/ganey)
* [Sven Lohrmann](https://github.com/malnvenshorn)
* [Andy Castille](https://github.com/klikini)
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
+157
View File
@@ -1,5 +1,162 @@
# OctoPrint Changelog
## 1.3.9 (2018-07-25)
### Still running OctoPrint 1.3.6? Heads-up!
OctoPrint 1.3.9 includes a couple of dependency updates whose update during switch to 1.3.9 are known to trigger an "update failed" message within OctoPrint's update dialog:
![](https://i.imgur.com/BbEZTlc.png)
The update did in fact succeed and the issue lies with a change in the underlying update mechanism concerning the dependencies. This problem has been fixed in 1.3.7/1.3.8 and versions prior to 1.3.6 aren't yet affected, so there you won't ever see this message there. If you are still running 1.3.6 though and updating from it, **simply run the update a second time through Settings > Software Update > Check for updates and clicking "Update now" in the reshown update notification**.
### Running NGINX as reverse proxy? Be sure to configure HTTP protocol version 1.1!
OctoPrint 1.3.9 updates the internal webserver Tornado from 4.0.2 to 4.5.3. Among many many fixes and improvements this also includes a change (actually a fix) in the websocket implementation that requires you to tell your NGINX to use HTTP 1.1 instead of the default 1.0 to talk to OctoPrint. You can do this by simply adding
```
proxy_http_version 1.1;
```
to the `location` config. The [configuration examples](https://discourse.octoprint.org/t/reverse-proxy-configuration-examples/1107) have been adjusted accordingly. See also [#2526](https://github.com/foosel/OctoPrint/issues/2526).
### Disabled IPv6 and now there are issues with the server after the update? Bind to IPv4 addresses only!
Starting with this release OctoPrint natively supports IPv6 and will attempt to bind to such addresses if it detects support in the underlying OS. If for whatever reason your OS doesn't support IPv6 even though Python's `socket` says otherwise, you can tell OctoPrint to bind to an IPv4 address only either via the `--host` command line parameter or `server.host` in `config.yaml`. Use `127.0.0.1` for localhost only, `0.0.0.0` for all IPv4 addresses or whatever specific IPv4 address you want to bind to.
### Plugin author and still dependent on the legacy plugin bundling flag? Fix your plugin!
As [announced with the release of OctoPrint 1.3.6](https://octoprint.org/blog/2017/12/12/new-release-1.3.6/), the legacy plugin bundling flag has now been removed again. [Make sure to check and if necessary fix your plugins](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/) if you haven't done that so far!
### Improvements
* [#652](https://github.com/foosel/OctoPrint/issues/652) & [#1545](https://github.com/foosel/OctoPrint/issues/1545) - Added name of user who started a job to job info (see also [#2576](https://github.com/foosel/OctoPrint/pull/2576)).
* [#1203](https://github.com/foosel/OctoPrint/issues/1203) & [#1905](https://github.com/foosel/OctoPrint/issues/1905) & [#1797](https://github.com/foosel/OctoPrint/issues/1797) & [#2514](https://github.com/foosel/OctoPrint/issues/2514) - Added support for plugins to override GCODE analysis provider and live print time estimation with their own implementations through two new hooks [`octoprint.filemanager.analysis.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-filemanager-analysis-factory) and [`octoprint.printer.estimation.factory`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-printer-estimation-factory).
* [#1217](https://github.com/foosel/OctoPrint/issues/1217) - Software Update Plugin: Block the UI in general when an update is in progress (even in browser windows that didn't start it and logged in as user) so that no prints can be accidentally started during that.
* [#1513](https://github.com/foosel/OctoPrint/issues/1513) - Option to allow sending `M0`/`M1` to the printer instead of swallowing it.
* [#2318](https://github.com/foosel/OctoPrint/issues/2318) - Gcode Viewer: Visualize "current" print head location with a marker.
* [#2351](https://github.com/foosel/OctoPrint/issues/2351) - Support for binding to IPv6 addresses. OctoPrint will now default to binding to `::` if IPv6 support is detected, and to `0.0.0.0` if not. Both the intermediary server and Tornado are instructed to bind their sockets to both IP versions. Positive IPv6 support detection relies on
* `socket.has_ipv6` being `True`
* `socket.IPPROTO_IPV6` and `socket.IPV6_V6ONLY` being available (or redefined in case of Windows) in order to ensure dual stack binding for the intermediary server)
* [#2379](https://github.com/foosel/OctoPrint/issues/2379) - File and plugin list now use the browser's native scrollbar instead of slimscroll. Slimscroll is still bundled though, in case third party plugins might depend on it.
* [#2487](https://github.com/foosel/OctoPrint/issues/2487) - Improved documentation of system command configuration (see also [#2498](https://github.com/foosel/OctoPrint/pull/2498)).
* [#2495](https://github.com/foosel/OctoPrint/pull/2495) - Removed unneeded filter from a template.
* [#2498](https://github.com/foosel/OctoPrint/pull/2498) - Improved documentation of the `async` flags of custom system commands.
* [#2512](https://github.com/foosel/OctoPrint/issues/2512) - Log files will now contain client IP as provided by first entry in X-Forwarded-For header (or more if `server.reverseProxy.trustDownstream` is configured accordingly).
* [#2518](https://github.com/foosel/OctoPrint/issues/2518) - Display absolute file upload date and time on hover (see also [#2630](https://github.com/foosel/OctoPrint/pull/2630)).
* [#2522](https://github.com/foosel/OctoPrint/issues/2522) - Perform logging to disk asynchronously to avoid slow downs caused by it.
* [#2541](https://github.com/foosel/OctoPrint/pull/2541) - Added link to instructions to reset passwords. Part of solving [#1239](https://github.com/foosel/OctoPrint/issues/1239).
* [#2543](https://github.com/foosel/OctoPrint/pull/2543) - Added `--no-cache-dir` to pip calls to work around `MemoryErrors`. See also [#2535](https://github.com/foosel/OctoPrint/pull/2535) and [pypa/pip#2984](https://github.com/pypa/pip/issues/2984) for more details.
* [#2558](https://github.com/foosel/OctoPrint/issues/2558) - Have the watched folder processor ignore hidden files.
* [#2572](https://github.com/foosel/OctoPrint/issues/2572) - More error resilience in `ItemListHelper` against empty child elements.
* [#2573](https://github.com/foosel/OctoPrint/pull/2573) - Added `M118` to commands to never automatically upper case.
* [#2583](https://github.com/foosel/OctoPrint/issues/2583) - Handle scripts that are part of a job like other lines coming from a job and thus allow them to be kept back using `job_on_hold`.
* [#2597](https://github.com/foosel/OctoPrint/issues/2597) - Disabled animation on cancel print confirmation.
* [#2463](https://github.com/foosel/OctoPrint/issues/2463) - Added documentation for `printingarea` and `dimensions` in `gcodeAnalysis` data model (see also [#2540](https://github.com/foosel/OctoPrint/pull/2540)).
* [#2615](https://github.com/foosel/OctoPrint/issues/2615) - Allowed more granular control over components to be upgraded through the software update plugin in its settings dialog.
* [#2620](https://github.com/foosel/OctoPrint/pull/2620) - Save `ItemListHelper` page sizes to local storage.
* [#2642](https://github.com/foosel/OctoPrint/pull/2642) - Added methods for adding and updating items to `ItemListHelper`.
* [#2644](https://github.com/foosel/OctoPrint/issues/2644) - Detect broken symlinks in configured folders on startup (see also further below).
* [#2648](https://github.com/foosel/OctoPrint/pull/2648) - Allowed class methods as callbacks in view models.
* A new API endpoint [`/api/settings/templates`](http://docs.octoprint.org/en/maintenance/api/settings.html#fetch-template-data) allows (admin only) access to information regarding the loaded templates and their order in the UI. That should allow plugins wishing to offer modification of ordering of tabs, sidebar components and so on to retrieve the data they need for that.
* Have the watched folder processor handle vanished files gracefully.
* Removed [`legacyPluginAssets` flag](https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/).
* Improved requirement detection in `octoprint_setuptools`, added unit tests for that.
* Bundled `sockjs-tornado` dependency. It hasn't been updated by the author in a while although there exist a number of issues plus patches for them, so we now vendor it.
* Disabled position logging on cancel by default. If you need this, please explicitly enable it, it is causing too many issues in the field with misbehaving firmware.
* Extended URL test API to allow whitelist/blacklist check for the returned content type, used that to verify that the webcam snapshot URL actually returns images.
* Added timeout for position logging on pause/cancel. This should work around firmware which doesn't provide a proper `M114` resport that might be unparseable so we won't get stuck in those cases.
* Migrated file storage metadata to json instead of YAML since it performs way way better.
* Added `missing linenumber` to recognized non-fatal error messages.
* Got rid of some Python 2 only code.
* Added sanity checks for configured folders (see also [#2644](https://github.com/foosel/OctoPrint/issues/2644)):
* on startup: check they are writable, if not revert to defaults
* on settings save: check they are writable, if not return an HTTP 400
* in the settings dialog: allow quick check of writability via test buttons
* Never send referrers with links
* Confirmation dialog helper now supports an HTML body.
* Sort serial ports naturally (e.g. `tty1`, `tty2`, ..., `tty10` instead of `tty1`, `tty10`, ...)
* Added `paused` and `resumed` action commands, [see here for details](http://docs.octoprint.org/en/maintenance/features/action_commands.html).
* Added two new hooks for firmware information, [`octoprint.comm.firmware.info`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-info) and [`octoprint.comm.firmware.capabilities`](http://docs.octoprint.org/en/maintenance/plugins/hooks.html#octoprint-comm-firmware-capabilities).
* Added view model list to `OctoPrint.coreui` UI module.
* Improved logging of `FatalStartupError`s.
* Add sanity check for disabled plugin list (see also [#2687 (comment)](https://github.com/foosel/OctoPrint/issues/2687#issuecomment-399797596)).
* Improve logging of exceptions triggered inside the state update worker (see also [#2715](https://github.com/foosel/OctoPrint/issues/2715)).
* Workaround for a potential `pip` issue when updating components through the Software Update plugin.
* Fix resend and timeout handling during an active `job_on_hold`.
* Updated some dependencies:
* Tornado to 4.5. Version 5 sadly has issues with web socket handling when access behind `haproxy`. So far no solution has been found, so we stay at 4.5 for now.
* jQuery to 3.3.1
* Several other Python dependencies
* Announcement Plugin: Don't reload all notifications if one is marked as read.
* Printer Safety Plugin: Added new detected firmwares:
* Anycubic Mega
* Malyan M200
* CR-10S
* all Repetier firmware versions prior to 0.92
* any firmware that reports the `THERMAL_PROTECTION` capability as disabled to thermal protection warning (see also [MarlinFirmware/Marlin#10465](https://github.com/MarlinFirmware/Marlin/pull/10465))
* Software Update Plugin: Default to `force_base = False` for version checks.
* Virtual Printer Plugin: Allow defining custom `M114` response formats.
### Bug fixes
* [#2333](https://github.com/foosel/OctoPrint/issues/2333) (Part 3/3) - Updated to PySerial 3.4 and utilize read and write cancelling to work around disconnect delays.
* [#2355](https://github.com/foosel/OctoPrint/issues/2355) - Fixed non deterministic sorting of files with missing fields (e.g. date for SD card files) in OctoPrint's frontend.
* [#2496](https://github.com/foosel/OctoPrint/issues/2496) - Fixed files API not allowing to walk through the directory tree unless fetching the full listing recursively by making sure that first level children nodes are always provided.
* [#2502](https://github.com/foosel/OctoPrint/pull/2502) - Fixed some invalid HTML
* [#2504](https://github.com/foosel/OctoPrint/pull/2504) & [#2532](https://github.com/foosel/OctoPrint/pull/2532) & [#2552](https://github.com/foosel/OctoPrint/pull/2552) - Fixed various typos
* [#2505](https://github.com/foosel/OctoPrint/issues/2505) - Fixed user switch to `_api` user on use of the global API key inside the browser.
* [#2509](https://github.com/foosel/OctoPrint/issues/2509) - Properly handle a printer reset while printing and don't get stuck in "Cancelling" state
* [#2517](https://github.com/foosel/OctoPrint/issues/2517) - Fixed baudrate negotiation with printers that need a bit of a delay between connection establishment and probing (e.g. Prusa MK3).
* [#2520](https://github.com/foosel/OctoPrint/issues/2520) - Fixed temperature presets being saved as strings instead of numbers.
* [#2533](https://github.com/foosel/OctoPrint/pull/2533) - Fixed API key copy button being enabled and generate button being disabled when no API key is set.
* [#2534](https://github.com/foosel/OctoPrint/issues/2534) - Fixed stale data in API key/user editor. See also [#2604](https://github.com/foosel/OctoPrint/pull/2604).
* [#2539](https://github.com/foosel/OctoPrint/issues/2539) - Made serial and baud rate lists consistent between connection panel and settings (see also [#2606](https://github.com/foosel/OctoPrint/pull/2606)).
* [#2547](https://github.com/foosel/OctoPrint/issues/2547) - Fixed `PrintFailed` being triggered in case of an error while processing the `afterPrintJobDone` GCODE script through introduction of `Resuming` and `Finishing` states.
* [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed "uninstall plugin" icon in Plugin Manager staying clickable even if disabled.
* [#2549](https://github.com/foosel/OctoPrint/issues/2549) - Fixed issue with detection uninstallation of disabled plugins (see also [#2650](https://github.com/foosel/OctoPrint/pull/2650)).
* [#2551](https://github.com/foosel/OctoPrint/issues/2551) - Fixed `0` being allowed for various intervals and timeouts where that values doesn't make sense.
* [#2554](https://github.com/foosel/OctoPrint/pull/2554) - Fixed a JSON example in the docs.
* [#2568](https://github.com/foosel/OctoPrint/pull/2568) - Fixed a dead link in the plugin hooks documentation in the docs.
* [#2579](https://github.com/foosel/OctoPrint/issues/2579) - Fixed print time left of "a couple of seconds" even after the print job has finished.
* [#2581](https://github.com/foosel/OctoPrint/issues/2581) & [#2587](https://github.com/foosel/OctoPrint/issues/2587) - Fixed OctoPrint getting stuck in "Pausing" or "Cancelling" state due to a race condition.
* [#2589](https://github.com/foosel/OctoPrint/issues/2589) - Added missing `typePath` field on API response for files on the printer's SD card.
* [#2591](https://github.com/foosel/OctoPrint/pull/2591) - Fixed markup of some HTML labels.
* [#2595](https://github.com/foosel/OctoPrint/pull/2595) - Fixed some UI appearance issues.
* [#2601](https://github.com/foosel/OctoPrint/issues/2601) - Properly handle relative paths for selection via `printer.select_file`.
* [#2621](https://github.com/foosel/OctoPrint/issues/2621) - Fixed framerate not being read from config for rendering unrendered timelapses.
* [#2625](https://github.com/foosel/OctoPrint/issues/2625) - Fixed incompatibility of OctoPrint's plugin subsystem with Python wheels, which are the default mode of installing plugins from pip version 10.0.0 onward.
* [#2632](https://github.com/foosel/OctoPrint/issues/2632) - Fixed race condition in resend handling on missing `ok`s.
* [#2675](https://github.com/foosel/OctoPrint/issues/2675) - Fixed a possible division by zero on SD upload.
* [#2677](https://github.com/foosel/OctoPrint/issues/2677) (regression) - Fix a deadlock when `job_on_hold` is utilized (causing issues at least with Octolapse)
* [#2683](https://github.com/foosel/OctoPrint/pull/2683) - Fixed two missing spaces in the german translation.
* [#2715](https://github.com/foosel/OctoPrint/issues/2715) (regression) - Fix broken estimator initialization on SD print start and resulting crash of the state update worker.
* [#2719](https://github.com/foosel/OctoPrint/issues/2719) (regression) - Fix live print time estimation
* [#2737](https://github.com/foosel/OctoPrint/issues/2737) (regression) - Fix print button being enabled even though no file is selected.
* [#2738](https://github.com/foosel/OctoPrint/issues/2738) (regression) - Limit the use of the `--no-cache-dir` argument added to `pip` calls to such versions of `pip` that already support it (anything newer than 1.5.6).
* Properly handle absolute paths for recovery data comparison.
* Fixed snapshot test button not resetting on error.
* Fixed decoupling of metadata logs in the file manager.
* Fixed "remember me" and IPv4/IPv6 sessions. This might also solve [#1881](https://github.com/foosel/OctoPrint/issues/1881).
* Removed Repetier resend repetition detection and handling code. It was buggy and introducing issues.
* Fixed script order: `beforePrint*` should always precede any commands from the print job.
* Only perform write tests on directories where necessary. Especially avoid them on page rendition to prevent misconfigured folders from triggering an HTTP 500. (regression)
### Special thanks to all the contributors!
Special thanks to everyone who contributed to this release, especially [@benlye](https://github.com/benlye), [@dadosch](https://github.com/dadosch), [@dforsi](https://github.com/dforsi), [@ganey](https://github.com/ganey),[@malnvenshorn](https://github.com/malnvenshorn), [@ntoff](https://github.com/ntoff), [@tedder](https://github.com/tedder) and [@vitormhenrique](https://github.com/vitormhenrique) for their PRs.
### More information
* [Commits](https://github.com/foosel/OctoPrint/compare/1.3.8...1.3.9)
* Release Candidates:
* [1.3.9rc1](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc1)
* [1.3.9rc2](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc2)
* [1.3.9rc3](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc3)
* [1.3.9rc4](https://github.com/foosel/OctoPrint/releases/tag/1.3.9rc4)
* A big **Thank you!** to everyone who reported back on these release candidates this time:
[arhi](https://github.com/arhi), [b-morgan](https://github.com/b-morgan), [brandstaetter](https://github.com/brandstaetter), [buchnoun](https://github.com/buchnoun), [CapnBry](https://github.com/CapnBry), [chatrat12](https://github.com/chatrat12), [ChrisHeerschap](https://github.com/ChrisHeerschap), [christianlupus](https://github.com/christianlupus), [chrisWhyTea](https://github.com/chrisWhyTea), [Crowlord](https://github.com/Crowlord), [ctgreybeard](https://github.com/ctgreybeard), [Cyberwizzard](https://github.com/Cyberwizzard), [DrJuJu](https://github.com/DrJuJu), [ejjenkins](https://github.com/ejjenkins), [fieldOfView](https://github.com/fieldOfView), [FormerLurker](https://github.com/FormerLurker), [four-of-four](https://github.com/four-of-four), [Galfinite](https://github.com/Galfinite), [gege2b](https://github.com/gege2b), [HFMan](https://github.com/HFMan), [jjlink](https://github.com/jjlink), [jneilliii](https://github.com/jneilliii), [JohnOCFII](https://github.com/JohnOCFII), [jwg3](https://github.com/jwg3), [kazibole](https://github.com/kazibole), [larp-welt](https://github.com/larp-welt), [McFly99](https://github.com/McFly99), [mod38](https://github.com/mod38), [ntoff](https://github.com/ntoff), [OutsourcedGuru](https://github.com/OutsourcedGuru), [paukstelis](https://github.com/paukstelis), [pingywon](https://github.com/pingywon), [pscrespo](https://github.com/pscrespo), [Rapsey](https://github.com/Rapsey), [tech-rat](https://github.com/tech-rat), [tedder](https://github.com/tedder), [thess](https://github.com/thess), [Thisismydigitalself](https://github.com/Thisismydigitalself), [tibmeister](https://github.com/tibmeister)
## 1.3.8 (2018-04-13)
### Bug fixes
View File
File renamed without changes.
+9 -1
View File
@@ -1,6 +1,12 @@
# OctoPrint
[![GitHub version](https://badge.fury.io/gh/foosel%2FOctoPrint.svg)](https://badge.fury.io/gh/foosel%2FOctoPrint)
![GitHub release](https://img.shields.io/github/release/foosel/OctoPrint.svg?colorB=brightgreen)
[![Travis build status](https://img.shields.io/travis/foosel/OctoPrint.svg)](https://travis-ci.org/foosel/OctoPrint)
[![Discourse topics](https://img.shields.io/discourse/https/discourse.octoprint.org/users.svg)](https://discourse.octoprint.org)
[![IRC](https://img.shields.io/badge/chat-on%20irc-brightgreen.svg)](https://chat.octoprint.org)
[![Twitter Follow](https://img.shields.io/twitter/follow/OctoPrint3d.svg?style=social&label=Follow)](https://twitter.com/OctoPrint3d)
OctoPrint provides a snappy web interface for controlling consumer 3D printers. It is Free Software
and released under the [GNU Affero General Public License V3](http://www.gnu.org/licenses/agpl.html).
@@ -9,6 +15,8 @@ Its website can be found at [octoprint.org](https://octoprint.org/?utm_source=gi
The community forum is available at [discourse.octoprint.org](https://discourse.octoprint.org/?utm_source=github&utm_medium=readme).
The official IRC channel is [#octoprint on freenode](https://chat.octoprint.org). Its logs can be found [here](https://freenode.logbot.info/octoprint).
The FAQ can be accessed by following [faq.octoprint.org](https://faq.octoprint.org/?utm_source=github&utm_medium=readme).
The documentation is located at [docs.octoprint.org](http://docs.octoprint.org).
+11 -6
View File
@@ -1,7 +1,7 @@
# Supporters
Development of this version of OctoPrint wouldn't have been possible without
[financial support by the community](http://octoprint.org/support-octoprint/) -
[the financial support by the community](https://octoprint.org/support-octoprint/) -
thanks to everyone who contributed!
## Patreon Patrons
@@ -12,6 +12,7 @@ thanks to everyone who contributed!
* Brad Jackson
* Brian E. Tyler
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
@@ -19,18 +20,23 @@ thanks to everyone who contributed!
* Ernesto Martinez
* F. Kunsmann
* Frank Sander
* Gary Deen
* George Robles
* günter weber
* Hydra Research LLC
* James Seigel
* Jeff Moe
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* Josh Daniels
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kodama Inc.
* Lewis Newby
* LulzBot®
* Makespace Madrid
* Mark Walker
@@ -38,21 +44,20 @@ thanks to everyone who contributed!
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Mohammed khorakiwala
* Noe Ruiz
* Patrick McGinnis
* Peter Schmehl
* Randy C. Will
* Robert Gusek
* Roger Strolz
* Roy Cortes
* Rudolff Vang
* Samer Najia
* Simon Hallam
* Stefan Krister
* Stephane Schittly
* Sven Mueller
* Symbiotic Devices
* Thomas Hatley
* Timothy D Hoogland
* Trent Shumay
and 1233 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1351 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
-1
View File
@@ -71,7 +71,6 @@
* [ddt](https://github.com/txels/ddt): MIT
* [mock](https://github.com/testing-cabal/mock): BSD
* [nose](http://pythonhosted.org/nose/): LGPL
* [pypandoc](https://github.com/bebraw/pypandoc): MIT
* [Sphinx](http://sphinx-doc.org/): BSD
* [sphinxcontrib-httpdomain](https://bitbucket.org/birkenfeld/sphinx-contrib/src/default/httpdomain/): BSD
* [sphinxcontrib-mermad](https://github.com/mgaitan/sphinxcontrib-mermaid): BSD
+56 -9
View File
@@ -263,8 +263,11 @@ File information
- Path to type of file in extension tree. E.g. ``["model", "stl"]`` for ``.stl`` files, or ``["machinecode", "gcode"]``
for ``.gcode`` files. ``["folder"]`` for folders.
Additional properties depend on ``type``. For a ``type`` value of ``folder``, see "Folders". For any other value
see "Files".
Additional properties depend on ``type``.
For a ``type`` value of ``folder``, see :ref:`Folders <sec-api-datamodel-files-folders>`.
For any other value see :ref:`Files <sec-api-datamodel-files-files>`.
.. _sec-api-datamodel-files-folders:
Folders
'''''''
@@ -280,13 +283,14 @@ Folders
* - ``children``
- 0..*
- Array of :ref:`File information items <sec-api-datamodel-files-file>`
- Contained children for entries of type ``folder``. Will only include children in subfolders in recursive
listings. Not present in non recursive listings, this might be revisited in the future.
- Contained children for entries of type ``folder``. On non recursive listings only present on first level
sub folders!
* - ``size``
- 0..1
- Number
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings, this might
be revisited in the future.
- The size of all files contained in the folder and its subfolders. Not present in non recursive listings!
.. _sec-api-datamodel-files-files:
Files
'''''
@@ -385,14 +389,58 @@ GCODE analysis information
- 0..1
- Object
- The estimated usage of filament
* - ``filament.length``
* - ``filament.tool{n}.length``
- 0..1
- Integer
- The length of filament used, in mm
* - ``filament.volume``
* - ``filament.tool{n}.volume``
- 0..1
- Float
- The volume of filament used, in cm³
* - ``dimensions``
- 0..1
- Object
- Information regarding the size of the printed model
* - ``dimensions.depth``
- 0..1
- Float
- The depth of the printed model, in mm
* - ``dimensions.height``
- 0..1
- Float
- The height of the printed model, in mm
* - ``dimensions.width``
- 0..1
- Float
- The width of the printed model, in mm
* - ``printingArea``
- 0..1
- Object
- Information regarding the size of the printing area
* - ``printingArea.maxX``
- 0..1
- Float
- The maximum X coordinate of the printed model, in mm
* - ``printingArea.maxY``
- 0..1
- Float
- The maximum Y coordinate of the printed model, in mm
* - ``printingArea.maxZ``
- 0..1
- Float
- The maximum Z coordinate of the printed model, in mm
* - ``printingArea.minX``
- 0..1
- Float
- The minimum X coordinate of the printed model, in mm
* - ``printingArea.minY``
- 0..1
- Float
- The minimum Y coordinate of the printed model, in mm
* - ``printingArea.minZ``
- 0..1
- Float
- The minimum Z coordinate of the printed model, in mm
.. _sec-api-datamodel-files-ref:
@@ -421,4 +469,3 @@ References
- URL
- The model from which this file was generated (e.g. an STL, currently not used). Never present for
folders.
+32 -3
View File
@@ -82,8 +82,37 @@ Retrieve all files
"path": "folderA",
"type": "folder",
"typePath": ["folder"],
"children": [],
"size": 1334
"children": [
{
"name": "whistle_v2_copy.gcode",
"path": "whistle_v2_copy.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "...",
"size": 1468987,
"date": 1378847754,
"origin": "local",
"refs": {
"resource": "http://example.com/api/files/local/folderA/whistle_v2_copy.gcode",
"download": "http://example.com/downloads/files/local/folderA/whistle_v2_copy.gcode"
},
"gcodeAnalysis": {
"estimatedPrintTime": 1188,
"filament": {
"length": 810,
"volume": 5.36
}
},
"print": {
"failure": 4,
"success": 23,
"last": {
"date": 1387144346,
"success": true
}
}
}
]
}
],
"free": "3.2GB"
@@ -443,7 +472,7 @@ Upload file or create folder
:form select: Whether to select the file directly after upload (``true``) or not (``false``). Optional, defaults
to ``false``. Ignored when creating a folder.
:form print: Whether to start printing the file directly after upload (``true``) or not (``false``). If set, ``select``
is implicitely ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
is implicitly ``true`` as well. Optional, defaults to ``false``. Ignored when creating a folder.
:form userdata: [Optional] An optional string that if specified will be interpreted as JSON and then saved along
with the file as metadata (metadata key ``userdata``). Ignored when creating a folder.
:form foldername: The name of the folder to create. Ignored when uploading a file.
+47 -7
View File
@@ -37,7 +37,7 @@ Besides that, OctoPrint also provides a :ref:`full state report of the printer <
OctoPrint's internal webserver is single threaded and can only handle one request at a time. This is
not a problem generally since asynchronous programming allows to just have one request which is waiting for
data from a long running backend operation to sleep while handling other requests. The internal framework
used for providing the REST API though, Flask, is based on WSGI, which is synchrounous in nature. This means
used for providing the REST API though, Flask, is based on WSGI, which is synchronous in nature. This means
that it is impossible to wait in a non blocking wait while handling a request on the REST API. So in order to
return the response of a command sent to the printer, the single thread of the webserver would have to be blocked
by the API while the response wasn't available yet. Which in turn would mean that the whole web server would
@@ -229,7 +229,7 @@ Issue a print head command
feedrate
Changes the feedrate factor to apply to the movements of the axes.
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 50 and 200%.
* ``factor``: The new factor, percentage between 50 and 200% as integer (``50`` to ``200``) or float (``0.5`` to ``2.0``).
All of these commands except ``feedrate`` may only be sent if the printer is currently operational and not printing.
Otherwise a :http:statuscode:`409` is returned.
@@ -280,9 +280,9 @@ Issue a print head command
HTTP/1.1 204 No Content
**Example feed rate request**
**Example feed rate request (1/2)**
Set the feed rate factor to 105%.
Set the feed rate factor to 105% using an integer argument.
.. sourcecode:: http
@@ -300,6 +300,26 @@ Issue a print head command
HTTP/1.1 204 No Content
**Example feed rate request (2/2)**
Set the feed rate factor to 105% using a float argument.
.. sourcecode:: http
POST /api/printer/printhead HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "feedrate",
"factor": 1.05
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``jog`` or ``home``.
:json number x: ``jog`` command: The amount to travel on the X axis in mm.
:json number y: ``jog`` command: The amount to travel on the Y axis in mm.
@@ -346,7 +366,7 @@ Issue a tool command
flowrate
Changes the flow rate factor to apply to extrusion of the tool.
* ``factor``: The new factor, percentage as integer or float (percentage divided by 100) between 75 and 125%.
* ``factor``: The new factor, percentage between 75 and 125% as integer (``75`` to ``125``) or float (``0.75`` to ``1.25``).
All of these commands may only be sent if the printer is currently operational and -- in case of ``select`` and
``extrude`` -- not printing. Otherwise a :http:statuscode:`409` is returned.
@@ -461,9 +481,9 @@ Issue a tool command
HTTP/1.1 204 No Content
**Example flow rate request**
**Example flow rate request (1/2)**
Set the flow rate factor to 95%.
Set the flow rate factor to 95% using an integer attribute.
.. sourcecode:: http
@@ -481,6 +501,26 @@ Issue a tool command
HTTP/1.1 204 No Content
**Example flow rate request (2/2)**
Set the flow rate factor to 95% using a float attribute.
.. sourcecode:: http
POST /api/printer/tool HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "flowrate",
"factor": 0.95
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``target``, ``offset``, ``select`` or ``extrude``.
:json object targets: ``target`` command: The target temperatures to set. Valid properties have to match the format ``tool{n}``.
:json object offsets: ``offset`` command: The offset temperature to set. Valid properties have to match the format ``tool{n}``.
+1 -1
View File
@@ -581,7 +581,7 @@ Profile
* - ``axes``
- 0..1
- Object
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maxium speed
- Description of the printer's axes properties, one entry each for ``x``, ``y``, ``z`` and ``e`` holding maximum speed
and whether this axis is inverted or not.
* - ``axes.{axis}.speed``
- 0..1
+261 -1
View File
@@ -86,6 +86,266 @@ Regenerate the system wide API key
:status 200: No error
:status 403: No admin rights
.. _sec-api-settings-fetchtemplaatedata:
Fetch template data
===================
.. http:get:: /api/settings/templates
Fetch data (currently only the sorting order) of all registered template components in the system.
Use this to get a full list of the identifiers of all UI components provided either by core OctoPrint or any
currently active plugins.
Example:
.. sourcecode:: http
GET /api/settings/templates HTTP/1.1
Host: example.com
X-Api-Key: abcdef...
.. sourcecode:: http
HTTP/1.1 200 OK
Content-Type: application/json
{
"order": {
"about": [
{
"id": "about",
"name": "About OctoPrint"
},
{
"id": "supporters",
"name": "Supporters"
},
{
"id": "authors",
"name": "Authors"
},
{
"id": "changelog",
"name": "Changelog"
},
{
"id": "license",
"name": "OctoPrint License"
},
{
"id": "thirdparty",
"name": "Third Party Licenses"
},
{
"id": "plugin_pluginmanager",
"name": "Plugin Licenses",
"plugin_id": "pluginmanager",
"plugin_name": "Plugin Manager"
}
],
"generic": [
{
"id": "plugin_announcements",
"name": "plugin_announcements",
"plugin_id": "announcements",
"plugin_name": "Announcement Plugin"
}
],
"navbar": [
{
"id": "settings",
"name": "settings"
},
{
"id": "systemmenu",
"name": "systemmenu"
},
{
"id": "plugin_announcements",
"name": "plugin_announcements",
"plugin_id": "announcements",
"plugin_name": "Announcement Plugin"
},
{
"id": "login",
"name": "login"
}
],
"plugin_pluginmanager_about_thirdparty": [],
"settings": [
{
"id": "section_printer",
"name": "Printer"
},
{
"id": "serial",
"name": "Serial Connection"
},
{
"id": "printerprofiles",
"name": "Printer Profiles"
},
{
"id": "temperatures",
"name": "Temperatures"
},
{
"id": "terminalfilters",
"name": "Terminal Filters"
},
{
"id": "gcodescripts",
"name": "GCODE Scripts"
},
{
"id": "section_features",
"name": "Features"
},
{
"id": "features",
"name": "Features"
},
{
"id": "webcam",
"name": "Webcam & Timelapse"
},
{
"id": "accesscontrol",
"name": "Access Control"
},
{
"id": "gcodevisualizer",
"name": "GCODE Visualizer"
},
{
"id": "api",
"name": "API"
},
{
"id": "section_octoprint",
"name": "OctoPrint"
},
{
"id": "server",
"name": "Server"
},
{
"id": "folders",
"name": "Folders"
},
{
"id": "appearance",
"name": "Appearance"
},
{
"id": "plugin_logging",
"name": "Logging",
"plugin_id": "logging",
"plugin_name": "Logging"
},
{
"id": "plugin_pluginmanager",
"name": "Plugin Manager",
"plugin_id": "pluginmanager",
"plugin_name": "Plugin Manager"
},
{
"id": "plugin_softwareupdate",
"name": "Software Update",
"plugin_id": "softwareupdate",
"plugin_name": "Software Update"
},
{
"id": "plugin_announcements",
"name": "Announcements",
"plugin_id": "announcements",
"plugin_name": "Announcement Plugin"
},
{
"id": "section_plugins",
"name": "Plugins"
},
{
"id": "plugin_action_command_prompt",
"name": "Action Command Prompt",
"plugin_id": "action_command_prompt",
"plugin_name": "Action Command Prompt Support"
},
{
"id": "plugin_cura",
"name": "CuraEngine (<= 15.04)",
"plugin_id": "cura",
"plugin_name": "CuraEngine (<= 15.04)"
}
],
"sidebar": [
{
"id": "plugin_printer_safety_check",
"name": "Printer Safety Warning",
"plugin_id": "printer_safety_check",
"plugin_name": "Printer Safety Check"
},
{
"id": "connection",
"name": "Connection"
},
{
"id": "state",
"name": "State"
},
{
"id": "files",
"name": "Files"
}
],
"tab": [
{
"id": "temperature",
"name": "Temperature"
},
{
"id": "control",
"name": "Control"
},
{
"id": "gcodeviewer",
"name": "GCode Viewer"
},
{
"id": "terminal",
"name": "Terminal"
},
{
"id": "timelapse",
"name": "Timelapse"
}
],
"usersettings": [
{
"id": "access",
"name": "Access"
},
{
"id": "interface",
"name": "Interface"
}
],
"wizard": []
}
}
Requires admin rights.
.. warning::
This API endpoint is in beta. Things might change. If you happen to want to develop against it, you should drop
me an email to make sure I can give you a heads-up when something changes in an backwards incompatible way.
:status 200: No error
:status 403: No admin rights
.. _sec-api-settings-datamodel:
Data model
@@ -106,7 +366,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
* - ``api.key``
- Only maps to ``api.key`` in ``config.yaml`` if request is sent with admin rights, set to ``n/a`` otherwise.
Starting with OctoPrint 1.3.3 setting this field via :ref:`the API <sec-api-settings-save>` is not possible,
only :ref:`regenerting it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
only :ref:`regenerating it <sec-api-settings-generateapikey>` is supported. Setting a custom value is only
possible through `config.yaml`.
* - ``api.allowCrossOrigin``
-
+31 -13
View File
@@ -30,6 +30,14 @@ Test paths or URLs
existence but also whether it is of the specified type. Optional.
* ``check_access``: A list of any of ``r``, ``w`` and ``x``. If present it will also
be checked if OctoPrint has read, write, execute permissions on the specified path.
* ``allow_create_dir``: If ``check_type`` is provided and set to ``dir``, this will allow
OctoPrint to create the target ``path`` as a directory if it doesn't yet exist to allow
for further tests.
* ``check_writable_dir``: If ``check_type`` is provided and set to ``dir``, this will
check that the provided ``path`` is a writable directory. OctoPrint not only check if the
permissions on the directory allow for writing but also attempt to write (and delete) a
small test file ``.testballoon.txt`` to the directory to test if writing is actually
possible.
The ``path`` command returns a :http:statuscode:`200` with a :ref:`path test result <sec-api-util-datamodel-pathtestresult>`
when the test could be performed. The status code of the response does NOT reflect the
@@ -65,6 +73,12 @@ Test paths or URLs
from the URL check will be returned as part of the check result as well. ``json`` will attempt
to parse the response as json and return the parsed result. ``true`` or ``bytes`` will base64 encode the body
and return that.
* ``content_type_whitelist``: Optional array of supported content types. If set and the URL returns a content
type not included in this list, the test will fail. E.g. ``["image/*", "text/plain"]``.
* ``content_type_blacklist``: Optional array of unsupported content types. If set and the URL returns a content
type included in this list, the test wil fail. E.g. ``["video/*"]``. Can be used together with ``content_type_whitelist``
to further limit broader content type definition, e.g. by putting ``image/*`` into the whitelist, but disallowing
PNG by including ``image/png`` on the blacklist.
The ``url`` command returns :http:statuscode:`200` with a :ref:`URL test result <sec-api-util-datamodel-urltestresult>`
when the test could be performed. The status code of the response does NOT reflect the
@@ -272,19 +286,23 @@ Test paths or URLs
"result": true
}
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
:json check_access: ``path`` command only: a list of access permissions to check for
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
:json host: ``server`` command only: the server to test
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
:json command: The command to execute, currently either ``path`` or ``url``
:json path: ``path`` command only: the path to test
:json check_type: ``path`` command only: the type of path to test for, either ``file`` or ``dir``
:json check_access: ``path`` command only: a list of access permissions to check for
:json allow_create_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to allow creation of the
directory if it doesn't yet exist (``true``) or not (``false``, default)
:json check_writable_dir: ``path`` command and ``checktype`` of ``dir`` only: whether to test if the directory
is writable by also trying to create a test file in it (``true``) or not (``false``, default)
:json url: ``url`` command only: the URL to test
:json status: ``url`` command only: one or more expected status codes
:json method: ``url`` command only: the HTTP method to use for the check
:json timeout: ``url`` and ``server`` commands only: the timeout for the test request
:json response: ``url`` command only: whether to include response data and if so in what form
:json host: ``server`` command only: the server to test
:json port: ``server`` command only: the port to test
:json protocol: ``server`` command only: the protocol to test
:statuscode 200: No error occurred
.. _sec-api-util-datamodel:
@@ -0,0 +1,110 @@
.. _sec-bundledplugins-action_command_prompt:
Action Command Prompt support
=============================
The OctoPrint Action Command Prompt Support Plugin comes bundled with OctoPrint (starting with 1.3.9).
It allows firmware to trigger dialog prompts for logged in users using :ref:`action commands <sec-features-action_commands>`, e.g. to wait
for user acknowledgement or allow the user to choose between options, and also to close the dialog again
in case its no longer needed, e.g. due to the user proceeding on the printer's own controller.
The choice of the user can be communicated back to the firmware via a configurable GCODE command with a
placeholder for the selected option's index.
.. _fig-bundledplugins-action_command_prompt-example:
.. figure:: ../images/bundledplugins-action_command_prompt-example.png
:align: center
:alt: Simple prompt example
A simple dialog example triggered by the firmware
.. _sec-bundledplugins-action_command_prompt-firststeps:
First Steps
-----------
In order for this plugin to work, you'll need to configure it with the command your firmware uses to accept
dialog selections. You can do that in the settings dialog.
Currently there is no agreed upon command for this since no firmware has yet made use of this feature, so OctoPrint
ships with an empty value here.
.. _sec-bundledplugins-action_command_prompt-configuration:
Configuring the plugin
----------------------
The plugin supports the following configuration keys:
* ``selection_command``: The command to send to the firmware on choice, including the ``{choice}`` placeholder, e.g. ``M876 S{choice}``.
You can modify them either through the plugin's configuration dialog under Settings, or by directly editing ``config.yaml``.
.. _sec-bundledplugins-action_command_prompt-action_commands:
Supported action commands
-------------------------
prompt_begin <message>
Starts the definition of a prompt dialog. ``<message>`` is the message to display to the user. Will be ignored
if a dialog is already defined.
prompt_choice <text>
Defines a choice with the associated ``<text>``. Will be ignored if no dialog has been defined yet.
prompt_button <text>
Same as ``prompt_choice``.
prompt_show
Tells OctoPrint that the dialog is now fully defined and to prompt the user. Will be ignored if no dialog is
defined yet.
prompt_end
Tells OctoPrint that the dialog should now be closed (e.g. the user made the choice on the printer directly instead
of through OctoPrint). Will be ignored if no dialog is defined yet.
.. _sec-bundledplugins-action_command_prompt-example:
Example communication with the firmware
---------------------------------------
.. _sec-bundledplugins-action_command_prompt-sourcecode:
To display the :ref:`above dialog <fig-bundledplugins-action_command_prompt-example>` the firmware sent these action commands:
.. code-block:: none
//action:prompt_begin Filament unloaded, swap then proceed
//action:prompt_choice Filament swapped
//action:prompt_show
If the user clicks the button, assuming a ``selection_command`` of ``M876 S{choice}`` is configured, OctoPrint
will send back ``M876 S0`` (0-based index).
A more complicated example with three options would be the following:
.. code-block:: none
//action:prompt_begin Filament runout detected. Please choose how to proceed:
//action:prompt_choice Swap filament
//action:prompt_choice Home X/Y and pause print
//action:prompt_choice Abort print
//action:prompt_show
This would produce the following output:
.. _fig-bundledplugins-action_command_prompt-example2:
.. figure:: ../images/bundledplugins-action_command_prompt-example2.png
:align: center
:alt: Another prompt example
Another dialog example triggered by the firmware
If the user selects "Abort print", OctoPrint will send ``2`` as selected choice.
Source code
-----------
The source of the Action Command Prompt Support plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/action_command_prompt``.
+3 -11
View File
@@ -57,18 +57,10 @@ path to that in the plugin settings.
Compiling for Raspbian
++++++++++++++++++++++
.. note::
Raspbian Jessie and later
~~~~~~~~~~~~~~~~~~~~~~~~~
A binary of CuraEngine 15.04.06 precompiled on Raspbian Jessie Lite 2016-03-18 is available
`here <http://bit.ly/octopi_cura_engine_150406>`__. Don't forget to make it
executable after copying it to your preferred destination on your Pi
(suggestion: ``/usr/local/bin``) with ``chmod +x cura_engine``. Use at your
own risk.
Raspbian Jessie
~~~~~~~~~~~~~~~
Building on Raspbian Jessie is as easy as::
Building on Raspbian Jessie and later is as easy as::
sudo apt-get -y install gcc-4.7 g++-4.7
git clone -b legacy https://github.com/Ultimaker/CuraEngine.git
+1
View File
@@ -7,6 +7,7 @@ Bundled Plugins
.. toctree::
:maxdepth: 2
action_command_prompt.rst
cura.rst
discovery.rst
logging.rst
+37 -21
View File
@@ -151,7 +151,7 @@ appearance or to modify the order and presence of the various UI components:
# order of settings, if settings plugins are registered gets extended internally by
# section_plugins and all settings plugins
settings
settings:
- section_printer
- serial
- printerprofiles
@@ -209,7 +209,7 @@ appearance or to modify the order and presence of the various UI components:
tab:
- plugin_helloworld
OctoPrint will then turn this into the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
OctoPrint will then display the tabs in the order ``plugin_helloworld``, ``temperature``, ``control``, ``gcodeviewer``,
``terminal``, ``timelapse`` plus any other plugins.
@@ -454,7 +454,7 @@ 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
# Parameters for the print time estimation 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.
@@ -560,6 +560,7 @@ Use the following settings to enable or disable OctoPrint features:
# Defaults to only M117.
autoUppercaseBlacklist:
- M117
- M118
.. _sec-configuration-config_yaml-folder:
@@ -616,15 +617,16 @@ Settings pertaining to the server side GCODE analysis implementation.
.. code-block:: yaml
# Maximum number of extruders to support/to sanity check for
maxExtruders: 10
gcodeAnalysis:
# Maximum number of extruders to support/to sanity check for
maxExtruders: 10
# Pause between each processed GCODE line in normal priority mode, seconds
throttle_normalprio: 0.01
# Pause between each processed GCODE line in normal priority mode, seconds
throttle_normalprio: 0.01
# Pause between each processed GCODE line in high priority mode (e.g. on fresh
# uploads), seconds
throttle_highprio: 0.0
# Pause between each processed GCODE line in high priority mode (e.g. on fresh
# uploads), seconds
throttle_highprio: 0.0
.. _sec-configuration-config_yaml-gcodeviewer:
@@ -635,16 +637,17 @@ Settings pertaining to the built in GCODE Viewer.
.. code-block:: yaml
# Whether to enable the GCODE viewer in the UI
enabled: true
gcodeViewer:
# Whether to enable the GCODE viewer in the UI
enabled: true
# Maximum size a GCODE file may have on mobile devices to automatically be loaded
# into the viewer, defaults to 2MB
mobileSizeThreshold: 2097152
# Maximum size a GCODE file may have on mobile devices to automatically be loaded
# into the viewer, defaults to 2MB
mobileSizeThreshold: 2097152
# Maximum size a GCODE file may have to automatically be loaded into the viewer,
# defaults to 20MB
sizeThreshold: 20971520
# Maximum size a GCODE file may have to automatically be loaded into the viewer,
# defaults to 20MB
sizeThreshold: 20971520
.. _sec-configuration-config_yaml-plugins:
@@ -893,7 +896,7 @@ Use the following settings to configure the serial connection to the printer:
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)
# the response skips on the ok)
triggerOkForM29: true
capabilities:
@@ -934,7 +937,7 @@ Use the following settings to configure the server:
# Settings if OctoPrint is running behind a reverse proxy (haproxy, nginx, apache, ...).
# These are necessary in order to make OctoPrint generate correct external URLs so
# that AJAX requests and download URLs work.
# that AJAX requests and download URLs work, and so that client IPs are read correctly.
reverseProxy:
# The request header from which to determine the URL prefix under which OctoPrint
@@ -968,6 +971,14 @@ Use the following settings to configure the server:
# (X-Forwarded-Host by default, see above) with forwarded requests.
hostFallback:
# List of trusted downstream servers for which to ignore the IP address when trying to determine
# the connecting client's IP address. If you have OctoPrint behind more than one reverse proxy
# you should add their IPs here so that they won't be interpreted as the client's IP. One reverse
# proxy will be handled correctly by default.
trustedDownstream:
- 192.168.1.254
- 192.168.23.42
# Settings for file uploads to OctoPrint, such as maximum allowed file size and
# header suffixes to use for streaming uploads. OctoPrint does some nifty things internally in
# order to allow streaming of large file uploads to the application rather than just storing
@@ -1092,7 +1103,12 @@ System
Use the following settings to add custom system commands to the "System" dropdown within OctoPrint's top bar.
Commands consist of a name, an action identifier, the commandline to execute and an optional confirmation message to
Commands consist of a ``name`` shown to the user, an ``action`` identifier used by the code and the actual
``command`` including any argument needed for its execution.
By default OctoPrint blocks until the command has returned so that the exit code can be used to show a success
or failure message; use the flag ``async: true`` for commands that don't return.
Optionally you can add a confirmation message to
display before actually executing the command (should be set to False if a confirmation dialog is not desired).
The following example defines a command for shutting down the system under Linux. It assumes that the user under which
+55 -44
View File
@@ -57,60 +57,71 @@ You can simulate certain conditions and communications through the terminal tab
All commands start with ``!!DEBUG:`` and are followed by the command you want to execute. For instance, sending
``!!DEBUG:action_disconnect`` will disconnect the printer. Sending ``!!DEBUG`` without command will show a help
message with all the available commands.
message with all the available commands:
Action Triggers
...............
.. code-block:: none
``action_pause``
Sends a "// action:pause" action trigger to the host.
OctoPrint Virtual Printer debug commands
``action_resume``
Sends a "// action:resume" action trigger to the host.
help
?
| This help.
``action_disconnect``
Sends a "// action:disconnect" action trigger to the host.
# Action Triggers
``action_custom <action>[ <parameters>]``
Sends a custom "// action:<action> <parameters>" action trigger to the host.
action_pause
| Sends a "// action:pause" action trigger to the host.
action_resume
| Sends a "// action:resume" action trigger to the host.
action_disconnect
| Sends a "// action:disconnect" action trigger to the
| host.
action_custom <action>[ <parameters>]
| Sends a custom "// action:<action> <parameters>"
| action trigger to the host.
Communication Errors
....................
# Communication Errors
``dont_answer``
Will not acknowledge the next command.
dont_answer
| Will not acknowledge the next command.
go_awol
| Will completely stop replying
trigger_resend_lineno
| Triggers a resend error with a line number mismatch
trigger_resend_checksum
| Triggers a resend error with a checksum mismatch
trigger_missing_checksum
| Triggers a resend error with a missing checksum
trigger_missing_lineno
| Triggers a "no line number with checksum" error w/o resend request
drop_connection
| Drops the serial connection
prepare_ok <broken ok>
| Will cause <broken ok> to be enqueued for use,
| will be used instead of actual "ok"
``go_awol``
Will completely stop replying.
# Reply Timing / Sleeping
``trigger_resend_lineno``
Triggers a resend error with a line number mismatch
sleep <int:seconds>
| Sleep <seconds> s
sleep_after <str:command> <int:seconds>
| Sleeps <seconds> s after each execution of <command>
sleep_after_next <str:command> <int:seconds>
| Sleeps <seconds> s after execution of next <command>
``trigger_resend_checksum``
Triggers a resend error with a checksum mismatch
# SD printing
``drop_connection``
Drops the serial connection
start_sd <str:file>
| Select and start printing file <file> from SD
select_sd <str:file>
| Select file <file> from SD, don't start printing it yet. Use
| start_sd to start the print
cancel_sd
| Cancels an ongoing SD print
``prepare_ok <broken ok>``
Will cause <broken ok> to be enqueued for use, will be used instead of actual "ok"
# Misc
Reply Timing / Sleeping
.......................
``sleep <int:seconds>``
Sleep <seconds> s
``sleep_after <str:command> <int:seconds>``
Sleeps <seconds> s after each execution of <command>
``sleep_after_next <str:command> <int:seconds>``
Sleeps <seconds> s after execution of next <command>
Misc
....
``help``
Show the available commands.
``send <str:message>``
Sends back <message>
send <str:message>
| Sends back <message>
reset
| Simulates a reset. Internal state will be lost.
+4 -4
View File
@@ -207,8 +207,8 @@ FolderAdded
Payload:
* ``storage``: the storage's identifier
* ``path``: the folders's path within its storage location
* ``name``: the folders's name
* ``path``: the folder's path within its storage location
* ``name``: the folder's name
.. note::
@@ -220,8 +220,8 @@ FolderRemoved
Payload:
* ``storage``: the storage's identifier
* ``path``: the folders's path within its storage location
* ``name``: the folders's name
* ``path``: the folder's path within its storage location
* ``name``: the folder's name
.. note::
+15
View File
@@ -29,12 +29,27 @@ pause
When this command is received from the printer, OctoPrint will pause a current print job just like if the
"Pause" button had been clicked.
paused
When this command is received from the printer, OctoPrint will pause a current print job but *without* triggering
any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware
that wants to signal to OctoPrint that a print should be paused but without any control interference from
OctoPrint, e.g. in case of a filament change fully managed by the firmware.
resume
When this command is received from the printer, OctoPrint will resume a current print job just like if
the "Resume" button had been clicked.
resumed
When this command is received from the printer, OctoPrint will resume a current print job but *without* triggering
any GCODE scripts or sending SD print control commands to the printer. This might be interesting for firmware
that wants to signal to OctoPrint that a print should be resumed but without any control interference from
OctoPrint, e.g. in case of a filament change fully managed by the firmware.
disconnect
When this command is received from the printer, OctoPrint will immediately disconnect from it.
If the bundled :ref:`Action Command Prompt Support Plugin <sec-bundledplugins-action_command_prompt>` is enabled (which
should be the case by default), OctoPrint will also interactive dialog creation through its :ref:`supported commands <sec-bundledplugins-action_command_prompt-action_commands>`.
Support for additional commands may be added by plugins by implementing a handler for the
:ref:`octoprint.comm.protocol.action <sec-plugins-hook-comm-protocol-action>` hook.
+1 -1
View File
@@ -75,7 +75,7 @@ All GCODE scripts have access to the following template variables through the te
* ``last_temperature``: Last actual and target temperature reported for all available tools and if available the
heated bed. This is a dictionary of key-value pairs. The keys are the indices of the available tools (``0``, ``1``,
...) and ``b`` for the heated bed. The values are a dictionary consisting of ``actual`` and ``target`` keys mapped
to the corresponding temperature in degrees celsius. Note that not all tools your printer has must necessarily be
to the corresponding temperature in degrees Celsius. Note that not all tools your printer has must necessarily be
present here, neither must the heated bed - it depends on whether OctoPrint has values for a tool or the bed. Also
note that ``actual`` and ``target`` might be ``None``.
* ``script``: An object wrapping the script's type (``gcode``) and name (e.g. ``afterPrintCancelled``) as ``script.type``
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

+1 -1
View File
@@ -417,7 +417,7 @@
Creates a custom exception class. ``name`` may be either a function in which case it will be used
as constructor for the new exception class, or a string, in which case a constructor with proper
``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be propery
``name``, ``message`` and ``stack`` attributes will be created. The class hierarchy will be properly
setup to subclass ``Error``.
**Example:**
+1 -1
View File
@@ -189,7 +189,7 @@
A boolean value, specifies whether to immediately start printing the file after the upload
completes (true) or not (false, default)
userdata
An optional object or a serialized JSON string of additional user supplised data to associate with
An optional object or a serialized JSON string of additional user supplied data to associate with
the uploaded file.
See :ref:`Upload file or create folder <sec-api-fileops-uploadfile>` for more details on the file upload API and
+1 -1
View File
@@ -85,7 +85,7 @@
.. js:function:: OctoPrintClient.socket.onRateTooHigh(measured, maximum)
Called by the socket client when the last measured round trip time was higher than the
current upper procesisng limit, indicating that the messages are now processed slower than
current upper processing limit, indicating that the messages are now processed slower than
the current rate requires and a slower rate might be necessary.
Can be overwritten with custom handler methods. The default implementation will call
+3 -3
View File
@@ -410,8 +410,8 @@ Now look at that!
Settings Galore: How to make parts of your plugin user adjustable
-----------------------------------------------------------------
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the english Wikipedia. But
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the german language node
Remember that Wikipedia link we added to our little link in the navigation bar? It links to the English Wikipedia. But
what if we want to allow our users to adjust that according to their wishes, e.g. to link to the German language node
about "Hello World" programs instead?
To allow your users to customized the behaviour of your plugin you'll need to implement the :class:`~octoprint.plugin.SettingsPlugin`
@@ -509,7 +509,7 @@ section doesn't yet exist in the file, create it):
# [...]
Restart OctoPrint. Not only should the URL displayed in the log file have changed, but also the link should now (after
a proper shift-reload) point to the german Wikipedia node about "Hello World" programs::
a proper shift-reload) point to the German Wikipedia node about "Hello World" programs::
2015-01-30 11:47:18,634 - octoprint.plugins.helloworld - INFO - Hello World! (more: https://de.wikipedia.org/wiki/Hallo-Welt-Programm)
+132 -2
View File
@@ -66,7 +66,7 @@ the general type of script for which to look for additions ("gcode") and the scr
return a 2-tuple of prefix and postfix if has something for either of those, otherwise ``None``. OctoPrint will then take
care to add prefix and suffix as necessary after a small round of preprocessing.
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/OctoPrint/OctoPrint-SoftwareUpdate>`_
Plugins can easily add their own hooks too. For example, the `Software Update Plugin <https://github.com/foosel/OctoPrint/tree/master/src/octoprint/plugins/softwareupdate>`_
declares a custom hook "octoprint.plugin.softwareupdate.check_config" which other plugins can add handlers for in order
to register themselves with the Software Update Plugin by returning their own update check configuration.
@@ -380,6 +380,52 @@ octoprint.cli.commands
OctoPrint's CLI.
:rtype: list
.. _sec-plugins-hook-comm-firmware-info:
octoprint.comm.firmware.info
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_info_hook(comm_instance, firmware_name, firmware_data, *args, **kwargs)
Be notified of firmware information received from the printer following an ``M115``.
Hook handlers may use this to react/adjust behaviour based on reported firmware data. OctoPrint parses the received
report line and provides the parsed ``firmware_name`` and additional ``firmware_data`` contained therein. A
response line ``FIRMWARE_NAME:Some Firmware Name FIRMWARE_VERSION:1.2.3 PROTOCOL_VERSION:1.0`` for example will
be turned into a ``dict`` looking like this:
.. code-block:: python
dict(FIRMWARE_NAME="Some Firmware Name",
FIRMWARE_VERSION="1.2.3",
PROTOCOL_VERSION="1.0")
``firmware_name`` will be ``Some Firmware Name`` in this case.
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str firmware_name: The name of the parsed capability
:param dict firmware_data: All data contained in the ``M115`` report
.. _sec-plugins-hook-comm-firmware-capabilities:
octoprint.comm.firmware.capabilities
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: firmware_capability_hook(comm_instance, capability, enabled, already_defined, *args, **kwargs)
Be notified of capability report entries received from the printer.
Hook handlers may use this to react to custom firmware capabilities. OctoPrint parses the received capability
line and provides the parsed ``capability`` and whether it's ``enabled`` to the handler. Additionally all already
parsed capabilities will also be provided.
Note that hook handlers will be called once per received capability line.
:param object comm_instance: The :class:`~octoprint.util.comm.MachineCom` instance which triggered the hook.
:param str capability: The name of the parsed capability
:param bool enabled: Whether the capability is reported as enabled or disabled
:param dict already_defined: Already defined capabilities (capability name mapped to enabled flag)
.. _sec-plugins-hook-comm-protocol-action:
octoprint.comm.protocol.action
@@ -389,7 +435,7 @@ octoprint.comm.protocol.action
React to a :ref:`action command <sec-features-action_commands>` received from the printer.
Hook handlers may use this to react to react to custom firmware messages. OctoPrint parses the received action
Hook handlers may use this to react to custom firmware messages. OctoPrint parses the received action
command ``line`` and provides the parsed ``action`` (so anything after ``// action:``) to the hook handler.
No returned value is expected.
@@ -801,6 +847,44 @@ octoprint.comm.transport.serial.factory
:rtype: A serial instance implementing implementing the methods ``readline(...)``, ``write(...)``, ``close()`` and
optionally ``baudrate`` and ``timeout`` attributes as described above.
.. _sec-plugins-hook-filemanager-analysis-factory:
octoprint.filemanager.analysis.factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: analysis_queue_factory_hook(*args, **kwargs)
Return additional (or replacement) analysis queue factories used for analysing uploaded files.
Should return a dictionary to merge with the existing dictionary of factories, mapping from extension tree leaf
to analysis queue factory. Analysis queue factories are expected to be :class:`~octoprint.filemanager.analysis.AbstractAnalysisQueue`
subclasses or factory methods taking one argument (the finish callback to be used by the queue implementation
to signal that an analysis has been finished to the system). See the source of :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue`
for an example.
By default, only one analysis queue factory is registered in the system, for file type ``gcode``: :class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue`.
This can be replaced by plugins using this hook, allowing other approaches to file analysis.
This is useful for plugins wishing to provide (alternative) methods of metadata analysis for printable files.
**Example:**
The following handler would replace the existing analysis queue for ``gcode`` files with a custom implementation:
.. code-block:: python
:linenos:
from octoprint.filemanager.analysis import AbstractAnalysisQueue
class MyCustomGcodeAnalysisQueue(AbstractAnalysisQueue):
# ... custom implementation here ...
def custom_gcode_analysis_queue(*args, **kwargs):
return dict(gcode=MyCustomGcodeAnalysisQueue)
:return: A dictionary of analysis queue factories, mapped by their targeted file type.
:rtype: dict
.. _sec-plugins-hook-filemanager-extensiontree:
octoprint.filemanager.extension_tree
@@ -903,6 +987,52 @@ octoprint.printer.factory
:return: The ``printer`` instance to use globally.
:rtype: PrinterInterface subclass or None
.. _sec-plugins-hook-printer-estimation-factory:
octoprint.printer.estimation.factory
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: print_time_estimator_factory(*args, **kwargs)
Return a :class:`~octoprint.printer.estimation.PrintTimeEstimator` subclass (or factory) to use for print time
estimation. This will be called on each start of a print or streaming job with a single parameter ``job_type``
denoting the type of job that was just started: ``local`` meaning a print of a local file through the serial connection,
``sdcard`` a print of a file stored on the printer's SD card, ``stream`` the streaming of a local file to the
printer's SD card.
This is useful for plugins wishing to provide alternative methods of live print time estimation.
If none of the registered factories return a ``PrintTimeEstimator`` subclass, the default :class:`~octoprint.printer.estimation.PrintTimeEstimator`
will be used.
**Example:**
The following example would replace the stock print time estimator with (a nonsensical) one that always estimates
two hours of print time left:
.. code-block:: python
from octoprint.printer.estimation import PrintTimeEstimator
class CustomPrintTimeEstimator(PrintTimeEstimator):
def __init__(self, job_type):
pass
def estimate(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
# always reports 2h as printTimeLeft
return 2 * 60 * 60, "estimate"
def create_estimator_factory(*args, **kwargs):
return CustomPrintTimeEstimator
__plugin_hooks__ = {
"octoprint.printer.estimation.factory": create_estimator_factory
}
:return: The :class:`~octoprint.printer.estimation.PrintTimeEstimator` class to use, or a factory method
:rtype: class or function
.. _sec-plugins-hook-server-http-bodysize:
octoprint.server.http.bodysize
+2 -2
View File
@@ -56,9 +56,9 @@ Example:
// more of your view model's implementation
}
// we don't explicitely declare a name property here
// we don't explicitly declare a name property here
// our view model will be registered under "myCustomViewModel" (implicit
// name derived from contructor name) and "yourCustomViewModel" (explicitely
// name derived from constructor name) and "yourCustomViewModel" (explicitly
// provided as additional name)
OCTOPRINT_VIEWMODELS.push({
construct: MyCustomViewModel,
+1 -1
View File
@@ -1,5 +1,5 @@
[metadata]
description-file = README.md
license_file = LICENSE.txt
[versioneer]
VCS = git
+50 -44
View File
@@ -14,43 +14,41 @@ import octoprint_setuptools
# Requirements for our application
INSTALL_REQUIRES = [
"flask>=0.9,<0.11",
"Jinja2>=2.8,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"flask>=0.10.1,<0.11",
"Jinja2>=2.8.1,<2.9", # Jinja 2.9 has breaking changes WRT template scope - we can't
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"werkzeug>=0.8.3,<0.9",
"tornado==4.0.2", # pinned for now, we need to migrate to a newer tornado, but due
# to some voodoo needed to get large streamed uploads and downloads
# to work that is probably not completely straightforward and therefore
# something for post-1.3.0-stable release
"sockjs-tornado>=1.0.3,<1.1",
"tornado==4.5.3",
#"sockjs-tornado>=1.0.3,<1.1", # current version is incompatible to tornado 5, we use a
# vendored one
"PyYAML>=3.10,<3.11",
"Flask-Login>=0.2.2,<0.3",
"Flask-Login>=0.2.11,<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,<3.5",
"netaddr>=0.7.17,<0.8",
"markdown>=2.6.9,<2.7",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.8.3,<0.9",
"sarge>=0.1.4,<0.2",
"netifaces>=0.10,<0.11",
"sarge==0.1.4", # 0.1.5 introduced a breaking change with regards to the async keyword. Pinning
# to 0.1.4 for now to work around this.
"netifaces>=0.10.6,<0.11",
"pylru>=1.0.9,<1.1",
"rsa>=3.2,<3.3",
"pkginfo>=1.2.1,<1.3",
"rsa>=3.2.3,<3.3",
"pkginfo>=1.4.2,<1.5",
"requests>=2.18.4,<3",
"semantic_version>=2.4.2,<2.5",
"psutil==5.4.3", # 5.4.4 introduced a breaking change concerning installing under non current
# setuptools versions. Pinning to 5.4.3 for now to work around this.
"psutil>=5.4.6,<5.5",
"Click>=6.2,<6.3",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
"chainmap>=1.0.2,<1.1",
"future>=0.15,<0.16",
"future>=0.15.2,<0.16",
"scandir>=1.3,<1.4",
"websocket-client>=0.40,<0.41",
"python-dateutil>=2.6,<2.7",
"wrapt>=1.10.10,<1.11",
"websocket-client>=0.40.0,<0.41",
"python-dateutil>=2.6.1,<2.7",
"wrapt>=1.10.11,<1.11",
"futures>=3.1.1,<3.2",
"emoji>=0.4.5,<0.5",
"monotonic>=1.3,<1.4",
@@ -74,9 +72,6 @@ EXTRA_REQUIRES = dict(
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
],
# Dependencies for developing OctoPrint plugins
@@ -94,6 +89,13 @@ DEPENDENCY_LINKS = []
#-----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
here = os.path.abspath(os.path.dirname(__file__))
def read_file_contents(path):
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def data_copy_build_py_factory(files, baseclass):
class data_copy_build_py(baseclass):
files = dict()
@@ -149,45 +151,49 @@ def params():
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "A snappy web interface for 3D printers"
long_description = open("README.md").read()
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
setup_requires = SETUP_REQUIRES
try:
import pypandoc
setup_requires += ["setuptools-markdown"]
long_description_markdown_filename = "README.md"
del pypandoc
except:
pass
classifiers = [
"Development Status :: 4 - Beta",
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
"Topic :: Printing",
"Topic :: System :: Networking :: Monitoring"
"Topic :: System :: Monitoring"
]
author = "Gina Häußge"
author_email = "osd@foosel.net"
url = "http://octoprint.org"
license = "AGPLv3"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://discourse.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
}
packages = find_packages(where="src")
package_dir = {
+60 -26
View File
@@ -50,15 +50,24 @@ del version_info
#~~ custom exceptions
class FatalStartupError(BaseException):
pass
class FatalStartupError(Exception):
def __init__(self, message, cause=None):
self.cause = cause
Exception.__init__(self, message)
def __str__(self):
result = Exception.__str__(self)
if self.cause:
return "{}: {}".format(result, str(self.cause))
else:
return result
#~~ init methods to bring up platform
def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
logging_config=None, debug=False, verbosity=0, uncaught_logger=None,
uncaught_handler=None, safe_mode=False, ignore_blacklist=False, after_preinit_logging=None,
after_settings=None, after_logging=None, after_safe_mode=None,
after_settings_init=None, after_logging=None, after_safe_mode=None, after_settings_valid=None,
after_event_manager=None, after_connectivity_checker=None,
after_plugin_manager=None, after_environment_detector=None):
kwargs = dict()
@@ -70,55 +79,80 @@ def init_platform(basedir, configfile, use_logging_file=True, logging_file=None,
if callable(after_preinit_logging):
after_preinit_logging(**kwargs)
settings = init_settings(basedir, configfile)
try:
settings = init_settings(basedir, configfile)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
kwargs["settings"] = settings
if callable(after_settings):
after_settings(**kwargs)
if callable(after_settings_init):
after_settings_init(**kwargs)
try:
logger = init_logging(settings,
use_logging_file=use_logging_file,
logging_file=logging_file,
default_config=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler)
except Exception as ex:
raise FatalStartupError("Could not initialize logging", cause=ex)
logger = init_logging(settings,
use_logging_file=use_logging_file,
logging_file=logging_file,
default_config=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=uncaught_logger,
uncaught_handler=uncaught_handler)
kwargs["logger"] = logger
if callable(after_logging):
after_logging(**kwargs)
settings_safe_mode = settings.getBoolean(["server", "startOnceInSafeMode"])
safe_mode = safe_mode or settings_safe_mode
kwargs["safe_mode"] = safe_mode
if callable(after_safe_mode):
after_safe_mode(**kwargs)
event_manager = init_event_manager(settings)
# now before we continue, let's make sure *all* our folders are sane
try:
settings.sanity_check_folders()
except Exception as ex:
raise FatalStartupError("Configured folders didn't pass sanity check", cause=ex)
if callable(after_settings_valid):
after_settings_valid(**kwargs)
try:
event_manager = init_event_manager(settings)
except Exception as ex:
raise FatalStartupError("Could not initialize event manager", cause=ex)
kwargs["event_manager"] = event_manager
if callable(after_event_manager):
after_event_manager(**kwargs)
connectivity_checker = init_connectivity_checker(settings, event_manager)
try:
connectivity_checker = init_connectivity_checker(settings, event_manager)
except Exception as ex:
raise FatalStartupError("Could not initialize connectivity checker", cause=ex)
kwargs["connectivity_checker"] = connectivity_checker
if callable(after_connectivity_checker):
after_connectivity_checker(**kwargs)
plugin_manager = init_pluginsystem(settings,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
kwargs["plugin_manager"] = plugin_manager
try:
plugin_manager = init_pluginsystem(settings,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
connectivity_checker=connectivity_checker)
except Exception as ex:
raise FatalStartupError("Could not initialize settings manager", cause=ex)
kwargs["plugin_manager"] = plugin_manager
if callable(after_plugin_manager):
after_plugin_manager(**kwargs)
environment_detector = init_environment_detector(plugin_manager)
kwargs["environment_detector"] = environment_detector
try:
environment_detector = init_environment_detector(plugin_manager)
except Exception as ex:
raise FatalStartupError("Could not initialize environment detector", cause=ex)
kwargs["environment_detector"] = environment_detector
if callable(after_environment_detector):
after_environment_detector(**kwargs)
@@ -198,7 +232,7 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"class": "octoprint.logging.handlers.OctoPrintStreamHandler",
"level": "DEBUG",
"formatter": "simple",
"stream": "ext://sys.stdout"
+7 -2
View File
@@ -86,8 +86,13 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error starting up OctoPrint.", err=True)
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
else:
from octoprint.server import Server
octoprint_server = Server(settings=settings,
+27 -6
View File
@@ -50,8 +50,6 @@ class AnalysisQueue(object):
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
At the moment, only the analysis of GCODE files for 3D printing is supported, through :class:`GcodeAnalysisQueue`.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
@@ -62,12 +60,13 @@ class AnalysisQueue(object):
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self):
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = dict(
gcode=GcodeAnalysisQueue(self._analysis_finished)
)
self._queues = dict()
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
@@ -307,6 +306,28 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
def __init__(self, finished_callback):
+71 -26
View File
@@ -153,7 +153,8 @@ class StorageInterface(object):
from root of base folder
:param function filter: a filter that matches the files that are to be returned, may be left out in which case no
filtering will take place
:param bool recursive: will also step into sub folders for building the complete list if set to True
:param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only
do one step down into sub folders to be able to populate the ``children``.
:return: a dictionary mapping entry names to entry data that represents the whole file list
"""
raise NotImplementedError()
@@ -176,14 +177,14 @@ class StorageInterface(object):
Removes the folder at ``path``
:param string path: the path of the folder to remove
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise and error will
be raised if the folder is not empty (apart from ``.metadata.yaml``) when it's to be removed
:param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will
be raised if the folder is not empty (apart from any metadata files) when it's to be removed
"""
raise NotImplementedError()
def copy_folder(self, source, destination):
"""
Copys the folder ``source`` to ``destination``
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
@@ -232,7 +233,7 @@ class StorageInterface(object):
def copy_file(self, source, destination):
"""
Copys the file ``source`` to ``destination``
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
@@ -443,7 +444,7 @@ class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
Metadata is managed inside ``.metadata.yaml`` files in the respective folders, indexed by the sanitized filenames
Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames
stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead.
This storage type implements :func:`path_on_disk`.
@@ -564,7 +565,7 @@ class LocalFileStorage(StorageInterface):
path = os.path.join(self.basefolder, path)
def last_modified_for_path(p):
metadata = os.path.join(p, ".metadata.yaml")
metadata = os.path.join(p, ".metadata.json")
if os.path.exists(metadata):
return max(os.stat(p).st_mtime, os.stat(metadata).st_mtime)
else:
@@ -633,7 +634,7 @@ class LocalFileStorage(StorageInterface):
empty = True
for entry in scandir(folder_path):
if entry.name == ".metadata.yaml":
if entry.name == ".metadata.json" or entry.name == ".metadata.yaml":
continue
empty = False
break
@@ -1114,7 +1115,7 @@ class LocalFileStorage(StorageInterface):
try:
print_time = float(print_time)
except:
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.yaml: {!r}".format(name, path, print_time))
self._logger.warn("Invalid print time value found in print history for {} in {}/.metadata.json: {!r}".format(name, path, print_time))
continue
if not printer_profile in former_print_times:
@@ -1277,7 +1278,7 @@ class LocalFileStorage(StorageInterface):
if metadata_dirty:
self._save_metadata(path, metadata)
def _list_folder(self, path, base="", entry_filter=None, recursive=True, **kwargs):
def _list_folder(self, path, base="", entry_filter=None, recursive=True, include_children=True, **kwargs):
if entry_filter is None:
entry_filter = kwargs.get("filter", None)
@@ -1385,8 +1386,14 @@ class LocalFileStorage(StorageInterface):
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
recursive=recursive)
entry_data["children"] = sub_result
elif include_children:
sub_result = self._list_folder(entry_path, base=path_in_location + "/", entry_filter=entry_filter,
recursive=False, include_children=False)
entry_data["children"] = sub_result
if not entry_filter or entry_filter(entry_name, entry_data):
# only add folders passing the optional filter
def get_size():
total_size = 0
for element in entry_data["children"].values():
@@ -1395,7 +1402,6 @@ class LocalFileStorage(StorageInterface):
return total_size
# only add folders passing the optional filter
extended_entry_data = dict()
extended_entry_data.update(entry_data)
if recursive:
@@ -1512,14 +1518,16 @@ class LocalFileStorage(StorageInterface):
if path in self._metadata_cache:
return deepcopy(self._metadata_cache[path])
metadata_path = os.path.join(path, ".metadata.yaml")
self._migrate_metadata(path)
metadata_path = os.path.join(path, ".metadata.json")
if os.path.exists(metadata_path):
with open(metadata_path) as f:
try:
import yaml
metadata = yaml.safe_load(f)
import json
metadata = json.load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
self._logger.exception("Error while reading .metadata.json from {path}".format(**locals()))
else:
if isinstance(metadata, dict):
self._metadata_cache[path] = deepcopy(metadata)
@@ -1528,27 +1536,63 @@ class LocalFileStorage(StorageInterface):
def _save_metadata(self, path, metadata):
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
metadata_path = os.path.join(path, ".metadata.json")
try:
import yaml
import json
with atomic_write(metadata_path) as f:
yaml.safe_dump(metadata, stream=f, default_flow_style=False, indent=" ", allow_unicode=True)
json.dump(metadata, f, indent=4, separators=(",", ": "))
except:
self._logger.exception("Error while writing .metadata.yaml to {path}".format(**locals()))
self._logger.exception("Error while writing .metadata.json to {path}".format(**locals()))
else:
self._metadata_cache[path] = deepcopy(metadata)
def _delete_metadata(self, path):
with self._get_metadata_lock(path):
metadata_path = os.path.join(path, ".metadata.yaml")
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting .metadata.yaml from {path}".format(**locals()))
metadata_files = (".metadata.json", ".metadata.yaml")
for metadata_file in metadata_files:
metadata_path = os.path.join(path, metadata_file)
if os.path.exists(metadata_path):
try:
os.remove(metadata_path)
except:
self._logger.exception("Error while deleting {metadata_file} from {path}".format(**locals()))
if path in self._metadata_cache:
del self._metadata_cache[path]
def _migrate_metadata(self, path):
# we switched to json in 1.3.9 - if we still have yaml here, migrate it now
import yaml
import json
with self._get_metadata_lock(path):
metadata_path_yaml = os.path.join(path, ".metadata.yaml")
metadata_path_json = os.path.join(path, ".metadata.json")
if not os.path.exists(metadata_path_yaml):
# nothing to migrate
return
if os.path.exists(metadata_path_json):
# already migrated
# TODO 1.3.10 Remove ".metadata.yaml" files
return
with open(metadata_path_yaml) as f:
try:
metadata = yaml.safe_load(f)
except:
self._logger.exception("Error while reading .metadata.yaml from {path}".format(**locals()))
return
if not isinstance(metadata, dict):
# looks invalid, ignore it
return
with atomic_write(metadata_path_json) as f:
json.dump(metadata, f, indent=4, separators=(",", ": "))
# TODO 1.3.10 Remove ".metadata.yaml" files
@contextmanager
def _get_metadata_lock(self, path):
with self._metadata_lock_mutex:
@@ -1560,8 +1604,9 @@ class LocalFileStorage(StorageInterface):
counter += 1
self._metadata_locks[path] = (counter, lock)
yield lock
yield lock
with self._metadata_lock_mutex:
counter = self._metadata_locks[path][0]
counter -= 1
if counter <= 0:
+40 -18
View File
@@ -6,10 +6,30 @@ import os
import re
import time
# noinspection PyCompatibility
import concurrent.futures
class AsyncLogHandlerMixin(logging.Handler):
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
def emit(self, record):
try:
self._executor.submit(self._emit, record)
except:
self.handleError(record)
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
logging.handlers.TimedRotatingFileHandler.__init__(self, *args, **kwargs)
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
@@ -17,7 +37,7 @@ class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler
os.remove(s)
class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
rollover_callbacks = []
@classmethod
@@ -25,32 +45,33 @@ class OctoPrintLogHandler(CleaningTimedRotatingFileHandler):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
CleaningTimedRotatingFileHandler.doRollover(self)
super(OctoPrintLogHandler, self).doRollover()
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
class SerialLogHandler(logging.handlers.RotatingFileHandler):
class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
_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}$")
class SerialLogHandler(AsyncLogHandlerMixin, 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
cls.do_rollover = True
def __init__(self, *args, **kwargs):
logging.handlers.RotatingFileHandler.__init__(self, *args, **kwargs)
super(SerialLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def emit(self, record):
logging.handlers.RotatingFileHandler.emit(self, record)
def shouldRollover(self, record):
return self.__class__._do_rollover
return self.do_rollover
def getFilesToDelete(self):
"""
@@ -64,7 +85,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if self.__class__._file_pattern.match(suffix):
if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
@@ -79,7 +100,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
os.remove(path)
def doRollover(self):
self.__class__._do_rollover = False
self.do_rollover = False
if self.stream:
self.stream.close()
@@ -88,7 +109,7 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
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)
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
@@ -98,8 +119,8 @@ class SerialLogHandler(logging.handlers.RotatingFileHandler):
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, level=logging.NOTSET):
logging.Handler.__init__(self, level=level)
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
@@ -133,6 +154,7 @@ class RecordingLogHandler(logging.Handler):
return len(self._buffer)
# noinspection PyAbstractClass
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
+76 -74
View File
@@ -630,30 +630,46 @@ class PluginManager(object):
def plugin_hooks(self):
return {key: map(lambda v: (v[1], v[2]), value) for key, value in self._plugin_hooks.items()}
def find_plugins(self, existing=None, ignore_uninstalled=True):
def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False):
added, found = self._find_plugins(existing=existing, ignore_uninstalled=ignore_uninstalled)
if incl_all_found:
return added, found
else:
return added
def _find_plugins(self, existing=None, ignore_uninstalled=True):
if existing is None:
existing = dict(self.plugins)
result = OrderedDict()
result_added = OrderedDict()
result_found = []
if self.plugin_folders:
try:
result.update(self._find_plugins_from_folders(self.plugin_folders,
existing,
ignored_uninstalled=ignore_uninstalled))
added, found = self._find_plugins_from_folders(self.plugin_folders,
existing,
ignored_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
self.logger.exception("Error fetching plugins from folders")
if self.plugin_entry_points:
existing.update(result)
existing.update(result_added)
try:
result.update(self._find_plugins_from_entry_points(self.plugin_entry_points,
existing,
ignore_uninstalled=ignore_uninstalled))
added, found = self._find_plugins_from_entry_points(self.plugin_entry_points,
existing,
ignore_uninstalled=ignore_uninstalled)
result_added.update(added)
result_found += found
except:
self.logger.exception("Error fetching plugins from entry points")
return result
return result_added, result_found
def _find_plugins_from_folders(self, folders, existing, ignored_uninstalled=True):
result = OrderedDict()
added = OrderedDict()
found = []
for folder in folders:
try:
@@ -691,7 +707,8 @@ class PluginManager(object):
# whatever this is, we ignore it
continue
if key in existing or key in result or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
found.append(key)
if key in existing or key in added or (ignored_uninstalled and key in self.marked_plugins["uninstalled"]):
# plugin is already defined, ignore it
continue
@@ -702,16 +719,17 @@ class PluginManager(object):
plugin.origin = FolderOrigin("folder", folder)
plugin.managable = not flagged_readonly and not actual_readonly
plugin.enabled = False
result[key] = plugin
added[key] = plugin
except:
self.logger.exception("Error processing folder entry {!r} from folder {}".format(entry, folder))
except:
self.logger.exception("Error processing folder {}".format(folder))
return result
return added, found
def _find_plugins_from_entry_points(self, groups, existing, ignore_uninstalled=True):
result = OrderedDict()
added = OrderedDict()
found = []
# let's make sure we have a current working set ...
working_set = pkg_resources.WorkingSet()
@@ -745,25 +763,25 @@ class PluginManager(object):
module_name = entry_point.module_name
version = entry_point.dist.version
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
found.append(key)
if key in existing or key in added or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
# plugin is already defined or marked as uninstalled, ignore it
continue
kwargs = dict(module_name=module_name, version=version)
package_name = None
package_name = entry_point.dist.project_name
try:
module_pkginfo = InstalledEntryPoint(entry_point)
entry_point_metadata = EntryPointMetadata(entry_point)
except:
self.logger.exception("Something went wrong while retrieving package info data for module %s" % module_name)
self.logger.exception("Something went wrong while retrieving metadata for module {}".format(module_name))
else:
kwargs.update(dict(
name=module_pkginfo.name,
summary=module_pkginfo.summary,
author=module_pkginfo.author,
url=module_pkginfo.home_page,
license=module_pkginfo.license
name=entry_point_metadata.name,
summary=entry_point_metadata.summary,
author=entry_point_metadata.author,
url=entry_point_metadata.home_page,
license=entry_point_metadata.license
))
package_name = module_pkginfo.name
plugin = self._import_plugin_from_module(key, **kwargs)
if plugin:
@@ -783,11 +801,11 @@ class PluginManager(object):
module_name,
plugin.location))
result[key] = plugin
added[key] = plugin
except:
self.logger.exception("Error processing entry point {!r} for group {}".format(entry_point, group))
return result
return added, found
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
author=None, url=None, license=None, bundled=False):
@@ -870,11 +888,26 @@ class PluginManager(object):
if force_reload is None:
force_reload = []
plugins = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload))
self.disabled_plugins.update(plugins)
added, found = self.find_plugins(existing=dict((k, v) for k, v in self.plugins.items() if not k in force_reload),
incl_all_found=True)
# let's clean everything we DIDN'T find first
removed = [key for key in self.enabled_plugins.keys() + self.disabled_plugins.keys() if key not in found]
for key in removed:
try:
del self.enabled_plugins[key]
except KeyError:
pass
try:
del self.disabled_plugins[key]
except KeyError:
pass
self.disabled_plugins.update(added)
# 1st pass: loading the plugins
for name, plugin in plugins.items():
for name, plugin in added.items():
try:
if not plugin.blacklisted and not plugin.forced_disabled:
self.load_plugin(name, plugin, startup=startup, initialize_implementation=initialize_implementations)
@@ -888,7 +921,7 @@ class PluginManager(object):
force_reload=force_reload)
# 2nd pass: enabling those plugins that need enabling
for name, plugin in plugins.items():
for name, plugin in added.items():
try:
if plugin.loaded and not plugin.forced_disabled:
if plugin.blacklisted:
@@ -1591,56 +1624,25 @@ def is_editable_install(install_dir, package, module, location):
return False
class InstalledEntryPoint(pkginfo.Installed):
def __init__(self, entry_point, metadata_version=None):
class EntryPointMetadata(pkginfo.Distribution):
def __init__(self, entry_point):
self.entry_point = entry_point
package = entry_point.module_name
pkginfo.Installed.__init__(self, package, metadata_version=metadata_version)
self.extractMetadata()
def read(self):
import sys
import glob
import warnings
opj = os.path.join
if self.package is not None:
package = self.package.__package__
if package is None:
package = self.package.__name__
metadata_files = ("METADATA", # wheel
"PKG-INFO") # egg
project = pkg_resources.to_filename(pkg_resources.safe_name(self.entry_point.dist.project_name))
if self.entry_point and self.entry_point.dist:
for metadata_file in metadata_files:
try:
return self.entry_point.dist.get_metadata(metadata_file)
except:
pass
package_pattern = '%s*.egg-info' % package
project_pattern = '%s*.egg-info' % project
file = getattr(self.package, '__file__', None)
if file is not None:
candidates = []
def _add_candidate(where):
candidates.extend(glob.glob(where))
for entry in sys.path:
if file.startswith(entry):
_add_candidate(opj(entry, 'EGG-INFO')) # egg?
for pattern in (package_pattern, project_pattern): # dist-installed?
_add_candidate(opj(entry, pattern))
dir, name = os.path.split(self.package.__file__)
for pattern in (package_pattern, project_pattern):
_add_candidate(opj(dir, pattern))
_add_candidate(opj(dir, '..', pattern))
for candidate in candidates:
if os.path.isdir(candidate):
path = opj(candidate, 'PKG-INFO')
else:
path = candidate
if os.path.exists(path):
with open(path) as f:
return f.read()
warnings.warn('No PKG-INFO found for package: %s' % self.package_name)
warnings.warn('No package metadata found for package: {}'.format(self.entry_point.module_name))
class Plugin(object):
+1 -1
View File
@@ -1443,7 +1443,7 @@ class SettingsPlugin(OctoPrintPlugin):
Make sure to protect sensitive information stored by your plugin that only logged in administrators (or users)
should have access to via :meth:`~octoprint.plugin.SettingsPlugin.get_settings_restricted_paths`. OctoPrint will
return its settings on the REST API even to anonymous clients, but will filter out fields it know are restricted,
return its settings on the REST API even to anonymous clients, but will filter out fields it knows are restricted,
therefore you **must** make sure that you specify sensitive information accordingly to limit access as required!
"""
@@ -0,0 +1,166 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.server import user_permission
import flask
from flask_babel import gettext
class Prompt(object):
def __init__(self, text):
self.text = text
self.choices = []
self._active = False
@property
def active(self):
return self._active
def add_choice(self, text):
self.choices.append(text)
def activate(self):
self._active = True
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._selection_command = None
def initialize(self):
self._selection_command = self._settings.get([b"selection_command"])
#~ AssetPlugin
def get_assets(self):
return dict(js=["js/action_command_prompt.js"])
#~ SettingsPlugin
def get_settings_defaults(self):
return dict(selection_command=None)
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._selection_command = self._settings.get([b"selection_command"])
#~ SimpleApiPlugin
def get_api_commands(self):
return dict(select=["choice"])
def on_api_command(self, command, data):
if command == "select":
if not user_permission.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.abort(409, "No active prompt")
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(400, "{!r} is not a valid value for choice".format(choice))
self._answer_prompt(choice)
def on_api_get(self, request):
if not user_permission.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
#~ TemplatePlugin
def get_template_configs(self):
return [dict(type="settings", name=gettext("Action Command Prompt"), custom_bindings=False)]
#~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith(b"prompt_"):
return
if self._selection_command is None:
self._logger.info("Got a prompt command from the printer but no selection command is defined")
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = b""
else:
action, parameter = parts
if action == b"prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warn("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
elif action == b"prompt_choice" or action == b"prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warn("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == b"prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warn("Prompt is already active")
return
self._show_prompt()
elif action == b"prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
#~ prompt handling
def _show_prompt(self):
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, dict(action="show",
text=self._prompt.text,
choices=self._prompt.choices))
def _close_prompt(self):
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, dict(action="close"))
def _answer_prompt(self, choice):
self._close_prompt()
self._printer.commands([self._selection_command.format(choice=choice)])
__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
"confirmation or selection prompts in OctoPrint")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
b"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler
}
@@ -0,0 +1,104 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintActionCommandPromptClient = function(base) {
this.base = base;
};
OctoPrintActionCommandPromptClient.prototype.get = function(refresh, opts) {
return this.base.get(this.base.getSimpleApiUrl("action_command_prompt"), opts);
};
OctoPrintActionCommandPromptClient.prototype.select = function(choice, opts) {
var data = {
choice: choice
};
return this.base.simpleApiCommand("action_command_prompt", "select", data, opts);
};
OctoPrintClient.registerPluginComponent("action_command_prompt", OctoPrintActionCommandPromptClient);
return OctoPrintActionCommandPromptClient;
});
$(function() {
function ActionCommandPromptViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self._modal = undefined;
self.requestData = function() {
if (!self.loginState.isUser()) return;
OctoPrint.plugins.action_command_prompt.get()
.done(self.fromResponse);
};
self.fromResponse = function(data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self._showPrompt(data.text, data.choices);
}
};
self._showPrompt = function(text, buttons) {
var opts = {
title: gettext("Message from your printer"),
message: text,
selections: buttons,
onselect: function(index) {
if (index > -1) {
self._select(index);
}
},
onclose: function() {
self._modal = undefined;
}
};
self._modal = showSelectionDialog(opts)
};
self._select = function(index) {
OctoPrint.plugins.action_command_prompt.select(index);
};
self._closePrompt = function() {
if (self._modal) {
self._modal.modal("hide");
}
};
self.onStartupComplete = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (!self.loginState.isUser()) return;
if (plugin !== "action_command_prompt") {
return;
}
switch (data.action) {
case "show": {
self._showPrompt(data.text, data.choices);
break;
}
case "close": {
self._closePrompt();
break;
}
}
}
}
OCTOPRINT_VIEWMODELS.push({
construct: ActionCommandPromptViewModel,
dependencies: ["loginStateViewModel"]
});
});
@@ -0,0 +1,11 @@
<h3>{{ _('Action Command Prompt Settings') }}</h3>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Selection Command') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.action_command_prompt.selection_command">
<div class="help-block">{{ _('Use this to define the command to tell the printer about the selection. OctoPrint will replace <code>{choice}</code> with the index of the selected choice. E.g. <code>M876 S{choice}</code> will become <code>M123 S1</code>') }}</div>
</div>
</div>
</form>
@@ -66,9 +66,11 @@ $(function() {
return link;
};
self.markRead = function(channel, until) {
self.markRead = function(channel, until, reload) {
if (!self.loginState.isAdmin()) return;
reload = !!reload;
var url = PLUGIN_BASEURL + "announcements/channels/" + channel;
var payload = {
@@ -83,7 +85,9 @@ $(function() {
data: JSON.stringify(payload),
contentType: "application/json; charset=UTF-8",
success: function() {
self.retrieveData()
if (reload) {
self.retrieveData()
}
}
})
};
@@ -28,7 +28,7 @@
<div class="content" data-bind="html: $data.summary"></div>
<div class="actions">
<span class="articlelink"><small><a data-bind="text: $root.cleanedLink($data), attr: {href: $data.link}" target="_blank" rel="noreferrer noopener"></a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
<span class="markread"><small><a href="javascript:void(0)" data-bind="click: function() { $root.markRead($parent.key, $data.published, true) }"><i class="fa fa-eye"></i> {{ _('Mark as last read') }}</a></small></span>
</div>
</article>
<!-- /ko -->
@@ -2,7 +2,7 @@
<label class="control-label" for="settings-cura-path">{{ _('Path to CuraEngine') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'">
<input type="text" class="input-block-level" data-bind="value: settings.plugins.cura.cura_engine, valueUpdate: 'afterkeydown'" id="settings-cura-path">
<button class="btn" type="button" data-bind="click: testEnginePath, enable: settings.plugins.cura.cura_engine(), css: {disabled: !settings.plugins.cura.cura_engine()}">{{ _('Test') }}</button>
</div>
<span class="help-block" data-bind="visible: pathBroken() || pathOk(), text: pathText"></span>
@@ -52,7 +52,7 @@
</form>
<small>{% trans %}
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>
here. Anything but those are <strong>not supported</strong>. That especially means 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>
+2 -2
View File
@@ -100,12 +100,12 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs"))
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs")
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append({
"name": entry.name,
@@ -333,7 +333,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
raise ValueError("Either URL or path must be provided")
self._logger.info("Installing plugin from {}".format(source))
pip_args = ["install", sarge.shell_quote(source)]
pip_args = ["install", sarge.shell_quote(source), '--no-cache-dir']
if dependency_links or self._settings.get_boolean(["dependency_links"]):
pip_args.append("--process-dependency-links")
@@ -672,7 +672,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.debug(u"{prefix} {line}".format(**locals()))
def _mark_plugin_enabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"]))
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
validator=lambda x: isinstance(x, list),
fallback=[]))
if plugin.key in disabled_list:
disabled_list.remove(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
@@ -687,7 +689,9 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._pending_enable.add(plugin.key)
def _mark_plugin_disabled(self, plugin, needs_restart=False):
disabled_list = list(self._settings.global_get(["plugins", "_disabled"]))
disabled_list = list(self._settings.global_get(["plugins", "_disabled"],
validator=lambda x: isinstance(x, list),
fallback=[]))
if not plugin.key in disabled_list:
disabled_list.append(plugin.key)
self._settings.global_set(["plugins", "_disabled"], disabled_list)
@@ -1 +1 @@
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog .slimScrollDiv{margin-bottom:20px;padding-right:12px}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{overflow:hidden;width:auto;height:300px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px 10px 5px 5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
table td.settings_plugin_plugin_manager_plugins_name,table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}table td.settings_plugin_plugin_manager_plugins_actions,table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}table td.settings_plugin_plugin_manager_plugins_actions a,table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}table td.settings_plugin_plugin_manager_plugins_actions a.disabled,table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
@@ -587,7 +587,7 @@ $(function() {
return;
}
if (!self.enableManagement()) {
if (!self.enableUninstall(data)) {
return;
}
@@ -23,13 +23,6 @@ table {
}
#settings_plugin_pluginmanager_repositorydialog {
.slimScrollDiv {
@scrollBar: 10px;
margin-bottom: 20px;
padding-right: @scrollBar + 2px;
}
h4 {
position: relative;
@@ -75,14 +68,15 @@ table {
}
#settings_plugin_pluginmanager_repositorydialog_list {
overflow: hidden;
width: auto;
height: 300px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
.entry {
border-bottom: 1px solid #ddd;
padding: 5px;
padding-right: 10px;
}
}
}
@@ -155,7 +155,7 @@
</form>
<div data-bind="visible: repositoryAvailable()">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="slimScrolledForeach: {data: repositoryplugins.paginatedItems, slimscroll: {height: '306px', size: '10px', distance: 0, railVisible: true, alwaysVisible: true, scrollBy: '102px'} }">
<div id="settings_plugin_pluginmanager_repositorydialog_list" data-bind="foreach: repositoryplugins.paginatedItems">
<div class="entry">
<div class="row-fluid">
<div class="span9">
@@ -245,57 +245,64 @@
<form class="form-horizontal">
<p>{% trans %}You should normally <strong>not</strong> have to change <strong>any</strong> of the following settings, they are purely provided for convenience here.{% endtrans %}</p>
<legend>{{ _('Plugin repository configuration') }}</legend>
<fieldset>
<legend>{{ _('Plugin repository configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
<span class="add-on">min</span>
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
</div>
</div>
</div>
<legend>{{ _('Notices configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
<span class="add-on">min</span>
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Repository cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_repositoryTtl">
<span class="add-on">min</span>
</div>
</div>
</div>
</div>
</fieldset>
<legend>{{ _('pip configuration') }}</legend>
<fieldset>
<legend>{{ _('Notices configuration') }}</legend>
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Additional arguments') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_pipForceUser"> {{ _('Force the use of the <code>--user</code> flag with <code>pip install</code>') }}
</label>
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Notices cache TTL') }}</label>
<div class="controls">
<div class="input-append">
<input type="number" class="input-mini" data-bind="value: config_noticesTtl">
<span class="add-on">min</span>
</div>
</div>
</div>
</div>
</fieldset>
<fieldset>
<legend>{{ _('pip configuration') }}</legend>
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
<label class="control-label">{{ _('Additional arguments') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_pipForceUser"> {{ _('Force the use of the <code>--user</code> flag with <code>pip install</code>') }}
</label>
</div>
</div>
</fieldset>
</form>
</div>
<div class="modal-footer">
@@ -8,6 +8,7 @@ import octoprint.plugin
from octoprint.events import Events
from octoprint.server import user_permission
from octoprint.util.version import get_comparable_version
import flask
from flask_babel import gettext
@@ -23,10 +24,47 @@ Learn more at https://faq.octoprint.org/warning-{warning_type}
"""
# Anet A8
ANETA8_M115_TEST = lambda name, data: name and name.lower().startswith("anet_a8_")
# Anycubic MEGA
ANYCUBIC_AUTHOR1 = "| Author: (Jolly, xxxxxxxx.CO.)".lower()
ANYCUBIC_AUTHOR2 = "| Author: (**Jolly, xxxxxxxx.CO.**)".lower()
ANYCUBIC_RECEIVED_TEST = lambda line: line and (ANYCUBIC_AUTHOR1 in line.lower() or ANYCUBIC_AUTHOR2 in line.lower())
# Creality CR-10s
CR10S_AUTHOR = " | Author: (CR-10Slanguage)".lower()
CR10S_RECEIVED_TEST = lambda line: line and CR10S_AUTHOR in line.lower()
# Malyan M200 aka Monoprice Select Mini
MALYANM200_M115_TEST = lambda name, data: name and name.lower().startswith("malyan") and data.get("MODEL") == "M200"
# Any Repetier versions < 0.92
REPETIER_BEFORE_092_M115_TEST = lambda name, data: name and name.lower().startswith("repetier") and extract_repetier_version(name) is not None and extract_repetier_version(name) < get_comparable_version("0.92")
# THERMAL_PROTECTION capability reported as disabled
THERMAL_PROTECTION_CAP_TEST = lambda cap, enabled: cap == "THERMAL_PROTECTION" and not enabled
SAFETY_CHECKS = {
"firmware-unsafe": (lambda name, data: name and name.lower().startswith("anet_a8_"),)
"firmware-unsafe": dict(m115=(ANETA8_M115_TEST, MALYANM200_M115_TEST, REPETIER_BEFORE_092_M115_TEST),
received=(ANYCUBIC_RECEIVED_TEST, CR10S_RECEIVED_TEST),
cap=(THERMAL_PROTECTION_CAP_TEST,),
message=u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
u"thermal runaway protection). This is a fire risk.")
}
def extract_repetier_version(name):
"""
Extracts the Repetier version number from the firmware name.
Example: "Repetier_0.91" => 0.91
"""
version = None
if "_" in name:
_, version = name.split("_", 1)
version = get_comparable_version(version, base=True)
return version
class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SimpleApiPlugin,
@@ -35,6 +73,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
# noinspection PyMissingConstructor
def __init__(self):
self._warnings = dict()
self._scan_received = True
##~~ TemplatePlugin API
@@ -57,9 +96,7 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
##~~ EventHandlerPlugin API
def on_event(self, event, payload):
if event == Events.FIRMWARE_DATA:
self._analyze_firmware_data(payload.get("name"), payload.get("data"))
elif event == Events.DISCONNECTED:
if event == Events.DISCONNECTED:
self._reset_warnings()
##~~ SimpleApiPlugin API
@@ -69,23 +106,47 @@ class PrinterSafetyCheckPlugin(octoprint.plugin.AssetPlugin,
return flask.make_response("Insufficient rights", 403)
return flask.jsonify(self._warnings)
##~~ GCODE received hook handler
def on_gcode_received(self, comm_instance, line, *args, **kwargs):
if self._scan_received:
self._run_checks("received", line)
return line
##~~ Firmware info hook handler
def on_firmware_info_received(self, comm_instance, firmware_name, firmware_data):
self._run_checks("m115", firmware_name, firmware_data)
self._scan_received = False
##~~ Firmware capability hook handler
def on_firmware_cap_received(self, comm_instance, cap, enabled, all_caps):
self._run_checks("cap", cap, enabled)
##~~ Helpers
def _analyze_firmware_data(self, name, data):
def _run_checks(self, check_type, *args, **kwargs):
changes = False
for warning_type, checks in SAFETY_CHECKS.items():
if any(x(name, data) for x in checks):
message = u"Your printer's firmware is known to lack mandatory safety features (e.g. " \
u"thermal runaway protection). This is a fire risk."
self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)),
warning_type=warning_type))
self._warnings[warning_type] = message
for warning_type, check_data in SAFETY_CHECKS.items():
checks = check_data.get(check_type)
message = check_data.get("message")
if not checks or not message:
continue
if any(x(*args, **kwargs) for x in checks):
self._register_warning(warning_type, message)
changes = True
if changes:
self._ping_clients()
def _register_warning(self, warning_type, message):
self._log_to_terminal(TERMINAL_SAFETY_WARNING.format(message="\n".join(textwrap.wrap(message, 75)),
warning_type=warning_type))
self._warnings[warning_type] = message
def _reset_warnings(self):
self._warnings.clear()
self._ping_clients()
@@ -107,4 +168,9 @@ __plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will n
"issue and inform you about that fact.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = PrinterSafetyCheckPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.on_gcode_received,
"octoprint.comm.protocol.firmware.info": __plugin_implementation__.on_firmware_info_received,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.on_firmware_cap_received
}
@@ -540,17 +540,17 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
json_data = flask.request.json
if "check" in json_data:
check_targets = map(lambda x: x.strip(), json_data["check"])
if "targets" in json_data:
targets = map(lambda x: x.strip(), json_data["targets"])
else:
check_targets = None
targets = None
if "force" in json_data and json_data["force"] in octoprint.settings.valid_boolean_trues:
force = True
else:
force = False
to_be_checked, checks = self.perform_updates(check_targets=check_targets, force=force)
to_be_checked, checks = self.perform_updates(targets=targets, force=force)
return flask.jsonify(dict(order=to_be_checked, checks=checks))
#~~ Asset API
@@ -771,13 +771,15 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._version_cache_dirty = True
return information, update_available, update_possible, online, error
def perform_updates(self, check_targets=None, force=False):
def perform_updates(self, force=False, **kwargs):
"""
Performs the updates for the given check_targets. Will update all possible targets by default.
:param check_targets: an iterable defining the targets to update, if not supplied defaults to all targets
:param targets: an iterable defining the targets to update, if not supplied defaults to all targets
"""
targets = kwargs.get("targets", kwargs.get("check_targets", None))
checks = self._get_configured_checks()
populated_checks = dict()
for target, check in checks.items():
@@ -788,9 +790,9 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
except:
self._logger.exception("Error while populating check prior to update for target {}".format(target))
if check_targets is None:
check_targets = populated_checks.keys()
to_be_updated = sorted(set(check_targets) & set(populated_checks.keys()))
if targets is None:
targets = populated_checks.keys()
to_be_updated = sorted(set(targets) & set(populated_checks.keys()))
if "octoprint" in to_be_updated:
to_be_updated.remove("octoprint")
tmp = ["octoprint"] + to_be_updated
@@ -37,7 +37,7 @@
};
OctoPrintSoftwareUpdateClient.prototype.check = function(force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
@@ -46,28 +46,28 @@
return this.checkEntries({entries: [], force: force, opts: opts});
};
OctoPrintSoftwareUpdateClient.prototype.update = function(entries, force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
OctoPrintSoftwareUpdateClient.prototype.update = function(targets, force, opts) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
entries = params.entries;
targets = params.targets;
force = params.force;
opts = params.opts;
}
entries = entries || [];
if (typeof entries == "string") {
entries = [entries];
targets = targets || [];
if (typeof targets === "string") {
targets = [targets];
}
var data = {
entries: entries,
targets: targets,
force: !!force
};
return this.base.postJson(this.updateUrl, data, opts);
};
OctoPrintSoftwareUpdateClient.prototype.updateAll = function(force, opts) {
if (arguments.length == 1 && _.isObject(arguments[0])) {
if (arguments.length === 1 && _.isObject(arguments[0])) {
var params = arguments[0];
force = params.force;
opts = params.opts;
@@ -92,8 +92,6 @@ $(function() {
self.settings = parameters[2];
self.popup = undefined;
self.forceUpdate = false;
self.updateInProgress = false;
self.waitingForRestart = false;
self.restartTimeout = undefined;
@@ -140,7 +138,6 @@ $(function() {
});
self.configurationDialog = undefined;
self.confirmationDialog = undefined;
self._updateClicked = false;
self.config_availableCheckTypes = ko.observableArray([]);
@@ -402,8 +399,6 @@ $(function() {
};
self.performCheck = function(showIfNothingNew, force, ignoreSeen) {
if (!self.loginState.isAdmin() && !self.settings.settings.plugins.softwareupdate.notify_users()) return;
self.checking(true);
OctoPrint.plugins.softwareupdate.check(force)
.done(function(data) {
@@ -504,6 +499,7 @@ $(function() {
self.performUpdate = function(force, items) {
if (!self.loginState.isAdmin()) return;
if (self.printerState.isPrinting()) return;
self.updateInProgress = true;
@@ -519,7 +515,7 @@ $(function() {
};
self._showPopup(options);
OctoPrint.plugins.softwareupdate.updateAll(force, items)
OctoPrint.plugins.softwareupdate.update(items, force)
.done(function(data) {
self.currentlyBeingUpdated = data.checks;
self._markWorking(gettext("Updating..."), gettext("Updating, please wait."));
@@ -538,7 +534,7 @@ $(function() {
});
};
self.update = function(force) {
self.update = function(force, items) {
if (self.updateInProgress) {
self._updateClicked = false;
return;
@@ -548,6 +544,10 @@ $(function() {
return;
}
if (items === undefined) {
items = self.availableAndPossible();
}
if (self.printerState.isPrinting()) {
self._showPopup({
title: gettext("Can't update while printing"),
@@ -556,24 +556,39 @@ $(function() {
});
self._updateClicked = false;
} else {
self.forceUpdate = (force == true);
self.confirmationDialog.modal("show");
var html = "<p>" + gettext("This will update the following components and restart the server:") + "</p>";
html += "<ul>";
_.each(items, function(item) {
html += "<li>"
+ "<span class=\"name\" title=\"" + item.fullNameRemote + "\">" + item.fullNameRemote + "</span>";
if (item.releaseNotes) {
html += "<br><a href=\"" + item.releaseNotes + "\" target=\"_blank\" rel=\"noreferrer noopener\">" + gettext("Release Notes") + "</a>"
}
html += "</li>";
});
html += "</ul>";
html += "<p>" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.") + "</p>"
+ "<p><strong>" + gettext("This action may disrupt any ongoing print jobs.") + "</strong></p>"
+ "<p>" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "</p>"
+ "<p>" + gettext("Are you sure you want to proceed?") + "</p>";
showConfirmationDialog({
title: gettext("Are you sure you want to update now?"),
html: html,
proceed: gettext("Proceed"),
onproceed: function() {
self.performUpdate((force === true),
_.map(items, function(info) { return info.key }));
},
onclose: function() {
self._updateClicked = false;
}
});
}
};
self.confirmUpdate = function() {
self.performUpdate(self.forceUpdate,
_.map(self.availableAndPossible(), function(info) { return info.key }));
self.confirmationDialog.modal("hide");
};
self.confirmationHidden = function() {
self._updateClicked = false;
};
self._showWorkingDialog = function(title) {
if (!self.loginState.isAdmin()) {
if (!self.loginState.isAdmin() && !self.loginState.isUser()) {
return;
}
@@ -628,9 +643,6 @@ $(function() {
self.workingDialog = $("#settings_plugin_softwareupdate_workingdialog");
self.workingOutput = $("#settings_plugin_softwareupdate_workingdialog_output");
self.configurationDialog = $("#settings_plugin_softwareupdate_configurationdialog");
self.confirmationDialog = $("#softwareupdate_confirmation_dialog");
self.confirmationDialog.on("hidden", self.confirmationHidden);
};
self.onServerDisconnect = function() {
@@ -1,35 +0,0 @@
<div id="softwareupdate_confirmation_dialog" class="modal hide fade">
<div class="modal-header">
<a href="#" class="close" data-dismiss="modal" aria-hidden="true">&times;</a>
<h3>{{ _('Are you sure you want to update now?') }}</h3>
</div>
<div class="modal-body">
<p>
{{ _('This will update the following components and restart the server:') }}
</p>
<ul>
<!-- ko foreach: availableAndPossible -->
<li>
<span class="name" data-bind="text: fullNameRemote, attr: {title: fullNameRemote}"></span>
<div class="releaseNotes" data-bind="visible: releaseNotes"><a data-bind="attr: {href: releaseNotes}" target="_blank" rel="noreferrer noopener">{{ _('Release Notes') }}</a></div>
</li>
<!-- /ko -->
</ul>
<p>
{{ _('Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.') }}
</p>
<p>
<strong>{{ _('This action may disrupt any ongoing print jobs.') }}</strong>
</p>
<p>
{{ _('Depending on your printer\'s controller and general setup, restarting OctoPrint may cause your printer to be reset.') }}
</p>
<p>
{{ _('Are you sure you want to proceed?') }}
</p>
</div>
<div class="modal-footer">
<a href="#" class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</a>
<a href="#" class="btn btn-danger" data-bind="click: function() { $root.confirmUpdate(); }">{{ _('Proceed') }}</a>
</div>
</div>
@@ -29,6 +29,7 @@
<span data-bind="invisible: !updateAvailable"><i class="fa fa-bell-o" title="{{ _('Update available') }}"></i></span>
</td>
<td class="settings_plugin_softwareupdate_column_information">
<a href="javascript:void(0)" data-bind="click: function() { $root.update(false, [$data]) }, visible: updateAvailable" class="btn btn-primary pull-right">{{ _('Update') }}</a>
<strong data-bind="text: displayName"></strong>: <span data-bind="text: displayVersion"></span> <span data-bind="invisible: updatePossible"><i class="fa fa-exclamation-triangle" data-bind="css: {'fa-unlink': !online && information && information.needs_online, 'fa-exclamation-triangle': !(!online && information && information.needs_online)}, attr: {title: $root.iconTitleForEntry($data)}"></i></span><br>
<small class="muted">
<span class="line">{{ _('Installed:') }} <span data-bind="text: information.local.name"></span></span>
@@ -58,7 +59,8 @@
</ul>
</div>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<button class="btn btn-primary btn-block" data-bind="click: function() { $root.update(); }, enable: !updateInProgress, css: {disabled: updateInProgress}"><i class="fa fa-spinner fa-spin" data-bind="visible: updateInProgress"></i> {{ _('Update all') }}</button>
<button class="btn btn-block" data-bind="click: function() { $root.performCheck(true, false, true); }, enable: !checking(), css: {disabled: checking()}"><i class="fa fa-spinner fa-spin" data-bind="visible: checking"></i> {{ _('Check for update now') }}</button>
<div>
<div><small><a href="#" class="muted" onclick="$(this).children().toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')"><i class="fa fa-caret-right"></i> {{ _('Advanced options') }}</a></small></div>
@@ -109,7 +111,9 @@
<h3 data-bind="text: workingTitle"></h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<pre id="settings_plugin_softwareupdate_workingdialog_output" class="pre-scrollable pre-output" style="height: 170px; display: none" data-bind="visible: loginState.isAdmin, foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message'}"></span></pre>
<p style="display: none" data-bind="visible: !loginState.isAdmin() && $root.working()"><i class="fa fa-spinner fa-spin"></i> {{ _('Update in progress, please wait.') }}</p>
<p style="display: none" data-bind="visible: !loginState.isAdmin() && !$root.working()">{{ _('Update done, please close this window.') }}</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.working()" aria-hidden="true">{{ _('Close') }}</button>
@@ -80,7 +80,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
install_arg = check["pip"].format(target_version=target_version, target=target_version)
logger.debug(u"Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["install", install_arg]
pip_args = ["install", install_arg, "--no-cache-dir"]
pip_kwargs = dict()
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
@@ -293,7 +293,7 @@ def get_latest(target, check, custom_compare=None, online=True):
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", True)
force_base = check.get("force_base", False)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
@@ -30,6 +30,7 @@ class VirtualPrinter(object):
send_regex = re.compile("send (.*)")
set_ambient_regex = re.compile("set_ambient ([-+]?[0-9]*\.?[0-9]+)")
start_sd_regex = re.compile("start_sd (.*)")
select_sd_regex = re.compile("select_sd (.*)")
def __init__(self, seriallog_handler=None, read_timeout=5.0, write_timeout=10.0):
import logging
@@ -168,72 +169,73 @@ class VirtualPrinter(object):
.format(read_timeout=self._read_timeout, write_timeout=self._write_timeout, options=settings().get(["devel", "virtualPrinter"]))
def _reset(self):
self._clearQueue(self.incoming)
self._clearQueue(self.outgoing)
self._clearQueue(self.buffered)
with self._incoming_lock:
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = [0.0] * self.extruderCount
self._lastF = 200
self._relative = True
self._lastX = 0.0
self._lastY = 0.0
self._lastZ = 0.0
self._lastE = [0.0] * self.extruderCount
self._lastF = 200
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._unitModifier = 1
self._feedrate_multiplier = 100
self._flowrate_multiplier = 100
self._sdCardReady = True
self._sdPrinting = False
if self._sdPrinter:
self._sdCardReady = True
self._sdPrinting = False
self._sdPrintingSemaphore.set()
self._sdPrinter = None
self._selectedSdFile = None
self._selectedSdFileSize = None
self._selectedSdFilePos = None
if self._sdPrinter:
self._sdPrinting = False
self._sdPrintingSemaphore.set()
self._sdPrinter = None
self._selectedSdFile = None
self._selectedSdFileSize = None
self._selectedSdFilePos = None
if self._writingToSdHandle:
try:
self._writingToSdHandle.close()
except:
pass
self._writingToSd = False
self._writingToSdHandle = None
self._newSdFilePos = None
if self._writingToSdHandle:
try:
self._writingToSdHandle.close()
except:
pass
self._writingToSd = False
self._writingToSdHandle = None
self._newSdFilePos = None
self._heatingUp = False
self._heatingUp = False
self.currentLine = 0
self.lastN = 0
self.currentLine = 0
self.lastN = 0
self._debug_awol = False
self._debug_sleep = None
self._sleepAfterNext.clear()
self._sleepAfter.clear()
self._debug_awol = False
self._debug_sleep = None
self._sleepAfterNext.clear()
self._sleepAfter.clear()
self._dont_answer = False
self._dont_answer = False
self._debug_drop_connection = False
self._debug_drop_connection = False
self._killed = False
self._killed = False
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
self._triggerResendWithMissingLinenoAt110 = True
self._triggerResendWithChecksumMismatchAt115 = True
self._triggerResendAt100 = True
self._triggerResendWithTimeoutAt105 = True
self._triggerResendWithMissingLinenoAt110 = True
self._triggerResendWithChecksumMismatchAt115 = True
if self._temperature_reporter is not None:
self._temperature_reporter.cancel()
self._temperature_reporter = None
if self._temperature_reporter is not None:
self._temperature_reporter.cancel()
self._temperature_reporter = None
if self._sdstatus_reporter is not None:
self._sdstatus_reporter.cancel()
self._sdstatus_reporter = None
if self._sdstatus_reporter is not None:
self._sdstatus_reporter.cancel()
self._sdstatus_reporter = None
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
self._send(item + "\n")
self._clearQueue(self.incoming)
self._clearQueue(self.outgoing)
self._clearQueue(self.buffered)
if settings().getBoolean(["devel", "virtualPrinter", "simulateReset"]):
for item in settings().get(["devel", "virtualPrinter", "resetLines"]):
self._send(item + "\n")
@property
def timeout(self):
@@ -529,19 +531,19 @@ class VirtualPrinter(object):
self._busyInterval = interval
def _gcode_M114(self, data):
if settings().getBoolean(["devel", "virtualPrinter", "reprapfwM114"]):
output = "X:{} Y:{} Z:{} {}".format(self._lastX,
self._lastY,
self._lastZ,
" ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)]))
else:
output = "X:{} Y:{} Z:{} E:{} Count: A:{} B:{} C:{}".format(self._lastX,
self._lastY,
self._lastZ,
self._lastE[self.currentExtruder],
int(self._lastX*100),
int(self._lastY*100),
int(self._lastZ*100))
m114FormatString = settings().get(["devel", "virtualPrinter", "m114FormatString"])
e = dict((index, value) for index, value in enumerate(self._lastE))
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(["E{}:{}".format(num, self._lastE[self.currentExtruder]) for num in range(self.extruderCount)])
output = m114FormatString.format(x=self._lastX,
y=self._lastY,
z=self._lastZ,
e=e,
f=self._lastF,
a=int(self._lastX*100),
b=int(self._lastY*100),
c=int(self._lastZ*100))
if not self._okBeforeCommandOutput:
ok = self._ok()
if ok:
@@ -679,8 +681,6 @@ class VirtualPrinter(object):
if not self._brokenResend:
self._sendOk()
if settings().getBoolean(["devel", "virtualPrinter", "repetierStyleResends"]):
request_resend()
request_resend()
def _debugTrigger(self, data):
@@ -735,9 +735,12 @@ class VirtualPrinter(object):
| Sleeps <seconds> s after execution of next <command>
# SD printing
start_sd <str:file>
| Start printing file <file> from SD
| Select and start printing file <file> from SD
select_sd <str:file>
| Select file <file> from SD, don't start printing it yet. Use
| start_sd to start the print
cancel_sd
| Cancels an ongoing SD print
@@ -794,6 +797,7 @@ class VirtualPrinter(object):
send_match = VirtualPrinter.send_regex.match(data)
set_ambient_match = VirtualPrinter.set_ambient_regex.match(data)
start_sd_match = VirtualPrinter.start_sd_regex.match(data)
select_sd_match = VirtualPrinter.select_sd_regex.match(data)
if sleep_match is not None:
interval = int(sleep_match.group(1))
@@ -823,8 +827,10 @@ class VirtualPrinter(object):
self._ambient_temperature = float(set_ambient_match.group(1))
self._send("// set ambient temperature to {}".format(self._ambient_temperature))
elif start_sd_match is not None:
self._selectSdFile(start_sd_match.group(1))
self._selectSdFile(start_sd_match.group(1), check_already_open=True)
self._startSdPrint()
elif select_sd_match is not None:
self._selectSdFile(select_sd_match.group(1))
except:
pass
@@ -844,10 +850,14 @@ class VirtualPrinter(object):
self._send(item)
self._send("End file list")
def _selectSdFile(self, filename):
def _selectSdFile(self, filename, check_already_open=False):
if filename.startswith("/"):
filename = filename[1:]
file = os.path.join(self._virtualSd, filename.lower())
if self._selectedSdFile == file and check_already_open:
return
if not os.path.exists(file) or not os.path.isfile(file):
self._send("open failed, File: %s." % filename)
else:
@@ -1159,10 +1169,10 @@ class VirtualPrinter(object):
def _finishSdPrint(self):
if not self._killed:
self._sdPrintingSemaphore.clear()
self._output("Done printing file")
self._selectedSdFilePos = 0
self._sdPrinting = False
self._sdPrinter = None
self._output("Done printing file")
def _waitForHeatup(self, heater, only_wait_if_higher):
delta = 1
+3 -3
View File
@@ -24,7 +24,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
from octoprint.settings import settings
from octoprint.util import deprecated
from octoprint.util import deprecated, natural_key
from octoprint.filemanager import FileDestinations
@@ -68,8 +68,8 @@ class PrinterInterface(object):
"""
import octoprint.util.comm as comm
return {
"ports": comm.serialList(),
"baudrates": comm.baudrateList(),
"ports": sorted(comm.serialList(), key=natural_key),
"baudrates": sorted(comm.baudrateList(), reverse=True),
"portPreference": settings().get(["serial", "port"]),
"baudratePreference": settings().getInt(["serial", "baudrate"]),
"autoconnect": settings().getBoolean(["serial", "autoconnect"])
+179 -14
View File
@@ -6,6 +6,166 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.settings import settings
class PrintTimeEstimator(object):
"""
Estimator implementation.
Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation.
"""
def __init__(self, job_type):
self.stats_weighing_until = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
self.validity_range = settings().getFloat(["estimation", "printTime", "validityRange"])
self.force_dumb_from_percent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"])
self.force_dumb_after_min = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"])
threshold = None
rolling_window = None
countdown = None
if job_type == "local" or job_type == "sdcard":
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
if job_type == "sdcard":
# 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
interval = settings().getFloat(["serial", "timeout", "sdStatus"])
if interval <= 0:
interval = 1.0
rolling_window = 15 / interval
# we are happy when one rolling window has been stable
countdown = rolling_window
self._data = TimeEstimationHelper(rolling_window=rolling_window, countdown=countdown, threshold=threshold)
def estimate(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 progress == 0 or printTime is None or cleanedPrintTime is None:
return None, None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self.estimate_total(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.stats_weighing_until:
# still inside weighing range, use part stats, part current estimate
sub_progress = progress * (1 / self.stats_weighing_until)
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.validity_range
max_progress = progress + self.validity_range
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.force_dumb_from_percent or \
cleanedPrintTime >= self.force_dumb_after_min * 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 estimate_total(self, progress, printTime):
if not progress or not printTime or not self._data:
return None
else:
return self._data.update(printTime / progress)
class TimeEstimationHelper(object):
STABLE_THRESHOLD = 0.1
@@ -34,23 +194,28 @@ class TimeEstimationHelper(object):
def is_stable(self):
return self._stable_counter is not None and self._stable_counter >= self._countdown
def update(self, newEstimate):
old_average_total = self.average_total
def update(self, new_estimate):
old_average_total = self.average_total
self._sum_total += newEstimate
self._totals.append(newEstimate)
self._count += 1
self._sum_total += new_estimate
self._totals.append(new_estimate)
self._count += 1
if old_average_total:
self._distances.append(abs(self.average_total - old_average_total))
if old_average_total:
self._distances.append(abs(self.average_total - old_average_total))
if -1.0 * self._threshold < self.average_distance < self._threshold:
if self._stable_counter is None:
self._stable_counter = 0
else:
self._stable_counter += 1
if -1.0 * self._threshold < self.average_distance < self._threshold:
if self._stable_counter is None:
self._stable_counter = 0
else:
self._stable_counter = None
self._stable_counter += 1
else:
self._stable_counter = None
if self.is_stable():
return self.average_total_rolling
else:
return None
@property
def average_total(self):
@@ -71,4 +236,4 @@ class TimeEstimationHelper(object):
if not self._count or self._count < self._rolling_window + 1:
return None
else:
return sum(self._distances) / len(self._distances)
return sum(self._distances) / len(self._distances)
+161 -233
View File
@@ -24,7 +24,7 @@ from octoprint.events import eventManager, Events
from octoprint.filemanager import FileDestinations, NoSuchStorage, valid_file_type
from octoprint.plugin import plugin_manager, ProgressPlugin
from octoprint.printer import PrinterInterface, PrinterCallback, UnknownScript, InvalidFileLocation, InvalidFileType
from octoprint.printer.estimation import TimeEstimationHelper
from octoprint.printer.estimation import PrintTimeEstimator
from octoprint.settings import settings
from octoprint.util import comm as comm
from octoprint.util import InvariantContainer
@@ -77,13 +77,21 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._streamingFinishedCallback = None
self._streamingFailedCallback = None
# job handling & estimation
self._selectedFileMutex = threading.RLock()
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"])
self._estimator_factory = PrintTimeEstimator
self._estimator = None
analysis_queue_hooks = plugin_manager().get_hooks("octoprint.printer.estimation.factory")
for name, hook in analysis_queue_hooks.items():
try:
estimator = hook()
if estimator is not None:
self._logger.info("Using print time estimator provided by {}".format(name))
self._estimator_factory = estimator
except:
self._logger.exception("Error while processing analysis queues from {}".format(name))
# comm
self._comm = None
@@ -113,7 +121,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=None,
lastPrintTime=None,
filament=self._dict(length=None,
volume=None)),
volume=None),
user=None),
progress=self._dict(completion=None,
filepos=None,
printTime=None,
@@ -126,6 +135,19 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
eventManager().subscribe(Events.METADATA_ANALYSIS_FINISHED, self._on_event_MetadataAnalysisFinished)
eventManager().subscribe(Events.METADATA_STATISTICS_UPDATED, self._on_event_MetadataStatisticsUpdated)
def _create_estimator(self, job_type=None):
if job_type is None:
with self._selectedFileMutex:
if self._selectedFile is None:
return
if self._selectedFile["sd"]:
job_type = "sdcard"
else:
job_type = "local"
self._estimator = self._estimator_factory(job_type)
#~~ handling of PrinterCallbacks
def register_callback(self, callback, *args, **kwargs):
@@ -174,14 +196,16 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
self._selectedFile["sd"],
self._selectedFile["user"])
def _on_event_MetadataStatisticsUpdated(self, event, data):
with self._selectedFileMutex:
if self._selectedFile:
self._setJobData(self._selectedFile["filename"],
self._selectedFile["filesize"],
self._selectedFile["sd"])
self._selectedFile["sd"],
self._selectedFile["user"])
#~~ progress plugin reporting
@@ -272,7 +296,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
for command in commands:
self._comm.sendCommand(command, tags=kwargs.get("tags", set()) | {"trigger:printer.commands"})
def script(self, name, context=None, must_be_set=True, *args, **kwargs):
def script(self, name, context=None, must_be_set=True, part_of_job=False, *args, **kwargs):
if self._comm is None:
return
@@ -280,6 +304,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
raise ValueError("name must be set")
result = self._comm.sendGcodeScript(name,
part_of_job=part_of_job,
replacements=context,
tags=kwargs.get("tags", set()) | {"trigger:printer.script"})
if not result and must_be_set:
@@ -418,26 +443,34 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self.commands("M221 S%d" % factor,
tags=kwargs.get("tags", set()) | {"trigger:printer.flow_rate"})
def select_file(self, path, sd, printAfterSelect=False, pos=None, *args, **kwargs):
def select_file(self, path, sd, printAfterSelect=False, user=None, pos=None, *args, **kwargs):
if self._comm is None or (self._comm.isBusy() or self._comm.isStreaming()):
self._logger.info("Cannot load file: printer not connected or currently busy")
return
self._validateJob(path, sd)
origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
if sd:
path_on_disk = "/" + path
path_in_storage = path
else:
path_on_disk = self._fileManager.path_on_disk(origin, path)
path_in_storage = self._fileManager.path_in_storage(origin, path_on_disk)
recovery_data = self._fileManager.get_recovery_data()
if recovery_data:
# clean up recovery data if we just selected a different file than is logged in that
expected_origin = FileDestinations.SDCARD if sd else FileDestinations.LOCAL
actual_origin = recovery_data.get("origin", None)
actual_path = recovery_data.get("path", None)
if actual_origin is None or actual_path is None or actual_origin != expected_origin or actual_path != path:
if actual_origin is None or actual_path is None or actual_origin != origin or actual_path != path_in_storage:
self._fileManager.delete_recovery_data()
self._printAfterSelect = printAfterSelect
self._posAfterSelect = pos
self._comm.selectFile("/" + path if sd else path, sd,
self._comm.selectFile("/" + path if sd else path_on_disk, sd,
user=user,
tags=kwargs.get("tags", set()) | {"trigger:printer.select_file"})
self._updateProgressData()
self._setCurrentZ(None)
@@ -460,34 +493,18 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
return self._comm.getFilePosition()
def start_print(self, pos=None, *args, **kwargs):
def start_print(self, pos=None, user=None, *args, **kwargs):
"""
Starts the currently loaded print job.
Only starts if the printer is connected and operational, not currently printing and a printjob is loaded
"""
if self._comm is None or not self._comm.isOperational() or self._comm.isPrinting():
return
with self._selectedFileMutex:
if self._selectedFile is None:
return
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
rolling_window = None
countdown = None
with self._selectedFileMutex:
if self._selectedFile["sd"]:
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
rolling_window = 15 / settings().get(["serial", "timeout", "sdStatus"])
# we are happy when one rolling window has been stable
countdown = rolling_window
self._timeEstimationData = TimeEstimationHelper(rolling_window=rolling_window,
threshold=threshold,
countdown=countdown)
self._fileManager.delete_recovery_data()
self._lastProgressReport = None
@@ -608,6 +625,12 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
def is_paused(self, *args, **kwargs):
return self._comm is not None and self._comm.isPaused()
def is_resuming(self, *args, **kwargs):
return self._comm is not None and self._comm.isResuming()
def is_finishing(self, *args, **kwargs):
return self._comm is not None and self._comm.isFinishing()
def is_error(self, *args, **kwargs):
return self._comm is not None and self._comm.isError()
@@ -646,7 +669,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
# probably something else added through a plugin, use it's basename as-is
remoteName = os.path.basename(filename)
self._timeEstimationData = TimeEstimationHelper()
self._create_estimator("stream")
self._comm.startFileTransfer(absolutePath, filename, "/" + remoteName,
special=not valid_file_type(filename, "gcode"),
tags=kwargs.get("tags", set()) | {"trigger:printer.add_sd_file"})
@@ -711,20 +734,6 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._messages.append(message)
self._stateMonitor.add_message(message)
def _estimateTotalPrintTime(self, progress, printTime):
if not progress or not printTime or not self._timeEstimationData:
return None
else:
newEstimate = printTime / progress
self._timeEstimationData.update(newEstimate)
result = None
if self._timeEstimationData.is_stable():
result = self._timeEstimationData.average_total_rolling
return result
def _updateProgressData(self, completion=None, filepos=None, printTime=None, printTimeLeft=None, printTimeLeftOrigin=None):
self._stateMonitor.set_progress(self._dict(completion=int(completion * 100) if completion is not None else None,
filepos=filepos,
@@ -744,144 +753,41 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printTime = self._comm.getPrintTime()
cleanedPrintTime = self._comm.getCleanedPrintTime()
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
with self._selectedFileMutex:
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
printTimeLeft, printTimeLeftOrigin = self._estimatePrintTimeLeft(progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType)
printTimeLeft = printTimeLeftOrigin = None
estimator = self._estimator
if progress is not None:
progress_int = int(progress * 100)
if self._lastProgressReport != progress_int:
self._lastProgressReport = progress_int
self._reportPrintProgressToPlugins(progress_int)
if progress == 0:
printTimeLeft = None
printTimeLeftOrigin = None
elif progress == 1.0:
printTimeLeft = 0
printTimeLeftOrigin = None
elif estimator is not None:
statisticalTotalPrintTime = None
statisticalTotalPrintTimeType = None
with self._selectedFileMutex:
if self._selectedFile and "estimatedPrintTime" in self._selectedFile \
and self._selectedFile["estimatedPrintTime"]:
statisticalTotalPrintTime = self._selectedFile["estimatedPrintTime"]
statisticalTotalPrintTimeType = self._selectedFile.get("estimatedPrintTimeType", None)
printTimeLeft, printTimeLeftOrigin = estimator.estimate(progress,
printTime,
cleanedPrintTime,
statisticalTotalPrintTime,
statisticalTotalPrintTimeType)
return self._dict(completion=progress * 100 if progress is not None else None,
filepos=filepos,
printTime=int(printTime) if printTime is not None else None,
printTimeLeft=int(printTimeLeft) if printTimeLeft is not None else None,
printTimeLeftOrigin=printTimeLeftOrigin)
def _estimatePrintTimeLeft(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
"""
Tries to estimate the print time left for the print job
This is somewhat horrible since accurate print time estimation is pretty much impossible to
achieve, considering that we basically have only two data points (current progress in file and
time needed for that so far - former prints or a file analysis might not have happened or simply
be completely impossible e.g. if the file is stored on the printer's SD card) and
hence can only do a linear estimation of a completely non-linear process. That's a recipe
for inaccurate predictions right there. Yay.
Anyhow, here's how this implementation works. This method gets the current progress in the
printed file (percentage based on bytes read vs total bytes), the print time that elapsed,
the same print time with the heat up times subtracted (if possible) and if available also
some statistical total print time (former prints or a result from the GCODE analysis).
1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`.
That thing tries to detect if the estimation based on our progress and time needed for that becomes
stable over time through a rolling window and only returns a result once that appears to be the
case.
2. If we have any statistical data (former prints or a result from the GCODE analysis)
but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage
in the print we do a percentage based weighing of the statistical data and the intelligent
estimate - the closer to the beginning of the print, the more precedence for the statistical
data, the closer to the cut off point, the more precendence for the intelligent estimate. This
is our preliminary total print time.
3. If the total print time is set, we do a sanity check for it. Based on the total print time
estimate and the time we already spent printing, we calculate at what percentage we SHOULD be
and compare that to the percentage at which we actually ARE. If it's too far off, our total
can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is
already higher than our total estimate.
4. If we do NOT have a total print time estimate yet but we've been printing for longer than
a configured amount of minutes or are further in the file than a configured percentage, we
also use the dumb estimate for now.
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and
hence can't produce to much computational overhead, we do not have any insight into the firmware implementation
with regards to planner setup and acceleration settings, we might not even have access to the printed file's
contents and such we need to find something that works "mostly" all of the time without costing too many
resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution
here makes me unhappy).
Args:
progress (float or None): Current percentage in the printed file
printTime (float or None): Print time elapsed so far
cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature
(if detectable).
statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile,
or estimated total print time from GCODE analysis.
statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time
of former prints) or "analysis"
Returns:
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
"""
if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
return None, 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, tools=None, bed=None):
if tools is None:
tools = dict()
@@ -912,7 +818,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if not os.path.isfile(path_on_disk):
raise InvalidFileLocation("{} does not exist in local storage, cannot select for printing".format(filename))
def _setJobData(self, filename, filesize, sd):
def _setJobData(self, filename, filesize, sd, user=None):
with self._selectedFileMutex:
if filename is not None:
if sd:
@@ -929,7 +835,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
"filename": path_in_storage,
"filesize": filesize,
"sd": sd,
"estimatedPrintTime": None
"estimatedPrintTime": None,
"user": user
}
else:
self._selectedFile = None
@@ -942,7 +849,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=None,
averagePrintTime=None,
lastPrintTime=None,
filament=None))
filament=None,
user=None))
return
estimatedPrintTime = None
@@ -993,7 +901,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
estimatedPrintTime=estimatedPrintTime,
averagePrintTime=averagePrintTime,
lastPrintTime=lastPrintTime,
filament=filament))
filament=filament,
user=user))
def _sendInitialStateUpdate(self, callback):
try:
@@ -1012,6 +921,8 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
printing=self.is_printing(),
cancelling=self.is_cancelling(),
pausing=self.is_pausing(),
resuming=self.is_resuming(),
finishing=self.is_finishing(),
closedOrError=self.is_closed_or_error(),
error=self.is_error(),
paused=self.is_paused(),
@@ -1044,28 +955,29 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
if self._comm is not None:
state_string = self._comm.getStateString()
# forward relevant state changes to gcode manager
if oldState == comm.MachineCom.STATE_PRINTING:
with self._selectedFileMutex:
if self._selectedFile is not None:
if state == comm.MachineCom.STATE_CLOSED or state == comm.MachineCom.STATE_ERROR or state == comm.MachineCom.STATE_CLOSED_WITH_ERROR:
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
if oldState in (comm.MachineCom.STATE_PRINTING,):
# if we were still printing and went into an error state, mark the print as failed
if state in (comm.MachineCom.STATE_CLOSED, comm.MachineCom.STATE_ERROR, comm.MachineCom.STATE_CLOSED_WITH_ERROR):
with self._selectedFileMutex:
if self._selectedFile is not None:
payload = self._payload_for_print_job_event()
if payload:
payload["time"] = self._comm.getPrintTime()
def finalize():
self._fileManager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
False,
self._printerProfileManager.get_current_or_default()["id"])
eventManager().fire(Events.PRINT_FAILED, payload)
def finalize():
self._fileManager.log_print(payload["origin"],
payload["path"],
time.time(),
payload["time"],
False,
self._printerProfileManager.get_current_or_default()["id"])
eventManager().fire(Events.PRINT_FAILED, payload)
thread = threading.Thread(target=finalize)
thread.daemon = True
thread.start()
thread = threading.Thread(target=finalize)
thread.daemon = True
thread.start()
self._analysisQueue.resume() # printing done, put those cpu cycles to good use
elif state == comm.MachineCom.STATE_PRINTING:
self._analysisQueue.pause() # do not analyse files while printing
@@ -1117,7 +1029,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
eventManager().fire(Events.UPDATED_FILES, {"type": "gcode"})
self._sdFilelistAvailable.set()
def on_comm_file_selected(self, full_path, size, sd):
def on_comm_file_selected(self, full_path, size, sd, user=None):
if full_path is not None:
payload = self._payload_for_print_job_event(location=FileDestinations.SDCARD if sd else FileDestinations.LOCAL,
print_job_file=full_path)
@@ -1125,22 +1037,27 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
else:
eventManager().fire(Events.FILE_DESELECTED)
self._setJobData(full_path, size, sd)
self._setJobData(full_path, size, sd, user=user)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
self._create_estimator()
if self._printAfterSelect:
self._printAfterSelect = False
self.start_print(pos=self._posAfterSelect)
self.start_print(pos=self._posAfterSelect, user=user)
def on_comm_print_job_started(self):
def on_comm_print_job_started(self, suppress_script=False):
self._stateMonitor.trigger_progress_update()
payload = self._payload_for_print_job_event()
if payload:
eventManager().fire(Events.PRINT_STARTED, payload)
self.script("beforePrintStarted",
context=dict(event=payload),
must_be_set=False)
if not suppress_script:
self.script("beforePrintStarted",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_print_job_done(self):
def on_comm_print_job_done(self, suppress_script=False):
self._fileManager.delete_recovery_data()
payload = self._payload_for_print_job_event()
@@ -1153,9 +1070,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
eventManager().fire(Events.PRINT_DONE, payload)
self.script("afterPrintDone",
context=dict(event=payload),
must_be_set=False)
if not suppress_script:
self.script("afterPrintDone",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def log_print():
self._fileManager.log_print(payload["origin"],
@@ -1186,7 +1105,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload["firmwareError"] = firmware_error
eventManager().fire(Events.PRINT_CANCELLING, payload)
def on_comm_print_job_cancelled(self):
def on_comm_print_job_cancelled(self, suppress_script=False):
self._setCurrentZ(None)
self._updateProgressData()
@@ -1195,9 +1114,11 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
payload["time"] = self._comm.getPrintTime()
eventManager().fire(Events.PRINT_CANCELLED, payload)
self.script("afterPrintCancelled",
context=dict(event=payload),
must_be_set=False)
if not suppress_script:
self.script("afterPrintCancelled",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def finalize():
self._fileManager.log_print(payload["origin"],
@@ -1212,26 +1133,30 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback):
thread.daemon = True
thread.start()
def on_comm_print_job_paused(self):
def on_comm_print_job_paused(self, suppress_script=False):
payload = self._payload_for_print_job_event(position=self._comm.pause_position.as_dict() if self._comm and self._comm.pause_position else None)
if payload:
eventManager().fire(Events.PRINT_PAUSED, payload)
self.script("afterPrintPaused",
context=dict(event=payload),
must_be_set=False)
if not suppress_script:
self.script("afterPrintPaused",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_print_job_resumed(self):
def on_comm_print_job_resumed(self, suppress_script=False):
payload = self._payload_for_print_job_event()
if payload:
eventManager().fire(Events.PRINT_RESUMED, payload)
self.script("beforePrintResumed",
context=dict(event=payload),
must_be_set=False)
if not suppress_script:
self.script("beforePrintResumed",
context=dict(event=payload),
part_of_job=True,
must_be_set=False)
def on_comm_file_transfer_started(self, filename, filesize):
def on_comm_file_transfer_started(self, filename, filesize, user=None):
self._sdStreaming = True
self._setJobData(filename, filesize, True)
self._setJobData(filename, filesize, True, user=user)
self._updateProgressData(completion=0.0, filepos=0, printTime=0)
self._stateMonitor.set_state(self._dict(text=self.get_state_string(), flags=self._getStateFlags()))
@@ -1389,20 +1314,23 @@ class StateMonitor(object):
self._change_event.set()
def _work(self):
while True:
self._change_event.wait()
try:
while True:
self._change_event.wait()
now = time.time()
delta = now - self._last_update
additional_wait_time = self._interval - delta
if additional_wait_time > 0:
time.sleep(additional_wait_time)
now = time.time()
delta = now - self._last_update
additional_wait_time = self._interval - delta
if additional_wait_time > 0:
time.sleep(additional_wait_time)
with self._state_lock:
data = self.get_current_data()
self._update_callback(data)
self._last_update = time.time()
self._change_event.clear()
with self._state_lock:
data = self.get_current_data()
self._update_callback(data)
self._last_update = time.time()
self._change_event.clear()
except:
logging.getLogger(__name__).exception("Looks like something crashed inside the state update worker. Please report this on the OctoPrint issue tracker (make sure to include logs!)")
def get_current_data(self):
with self._progress_lock:
+93 -57
View File
@@ -6,7 +6,7 @@ __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
import uuid
from sockjs.tornado import SockJSRouter
from octoprint.vendor.sockjs.tornado import SockJSRouter
from flask import Flask, g, request, session, Blueprint, Request, Response, current_app
from flask_login import LoginManager, current_user, session_protected, user_logged_out
from flask_principal import Principal, Permission, RoleNeed, identity_loaded, identity_changed, UserNeed, AnonymousIdentity
@@ -71,6 +71,7 @@ import octoprint.plugin
import octoprint.timelapse
import octoprint._version
import octoprint.util
import octoprint.util.net
import octoprint.filemanager.storage
import octoprint.filemanager.analysis
import octoprint.slicing
@@ -160,7 +161,7 @@ def unauthorized_user():
class Server(object):
def __init__(self, settings=None, plugin_manager=None, connectivity_checker=None, environment_detector=None,
event_manager=None, host="0.0.0.0", port=5000, debug=False, safe_mode=False, allow_root=False,
event_manager=None, host=None, port=None, debug=False, safe_mode=False, allow_root=False,
octoprint_daemon=None):
self._settings = settings
self._plugin_manager = plugin_manager
@@ -217,12 +218,29 @@ class Server(object):
debug = self._debug
safe_mode = self._safe_mode
if self._host is None:
host = self._settings.get(["server", "host"])
if host is None:
if octoprint.util.net.HAS_V6:
host = "::"
else:
host = "0.0.0.0"
self._host = host
if ":" in self._host and not octoprint.util.net.HAS_V6:
raise RuntimeError("IPv6 host address {!r} configured but system doesn't support IPv6".format(self._host))
if self._port is None:
self._port = self._settings.getInt(["server", "port"])
if self._port is None:
self._port = 5000
self._logger = logging.getLogger(__name__)
self._setup_heartbeat_logging()
pluginManager = self._plugin_manager
# monkey patch a bunch of stuff
util.tornado.fix_ioloop_scheduling()
util.tornado.fix_json_encode()
util.flask.enable_additional_translations(additional_folders=[self._settings.getBaseFolder("translations")])
@@ -254,7 +272,17 @@ class Server(object):
printerProfileManager = PrinterProfileManager()
eventManager = self._event_manager
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue()
analysis_queue_factories = dict(gcode=octoprint.filemanager.analysis.GcodeAnalysisQueue)
analysis_queue_hooks = pluginManager.get_hooks("octoprint.filemanager.analysis.factory")
for name, hook in analysis_queue_hooks.items():
try:
additional_factories = hook()
analysis_queue_factories.update(**additional_factories)
except:
self._logger.exception("Error while processing analysis queues from {}".format(name))
analysisQueue = octoprint.filemanager.analysis.AnalysisQueue(analysis_queue_factories)
slicingManager = octoprint.slicing.SlicingManager(self._settings.getBaseFolder("slicingProfiles"), printerProfileManager)
storage_managers = dict()
@@ -286,17 +314,6 @@ class Server(object):
eventManager.subscribe(events.Events.SETTINGS_UPDATED, on_settings_update)
# setup access control
userManagerName = self._settings.get(["accessControl", "userManager"])
try:
clazz = octoprint.util.get_class(userManagerName)
userManager = clazz()
except:
self._logger.exception("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(userManagerName))
userManager = octoprint.users.FilebasedUserManager()
finally:
userManager.enabled = self._settings.getBoolean(["accessControl", "enabled"])
components = dict(
plugin_manager=pluginManager,
printer_profile_manager=printerProfileManager,
@@ -471,11 +488,6 @@ class Server(object):
## Tornado initialization starts here
if self._host is None:
self._host = self._settings.get(["server", "host"])
if self._port is None:
self._port = self._settings.getInt(["server", "port"])
ioloop = IOLoop()
ioloop.install()
@@ -618,8 +630,18 @@ 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=self._settings.getInt(["server", "maxSize"]))
self._server.listen(self._port, address=self._host)
trusted_downstream = self._settings.get(["server", "reverseProxy", "trustedDownstream"])
if not isinstance(trusted_downstream, list):
self._logger.warn("server.reverseProxy.trustedDownstream is not a list, skipping")
trusted_downstreams = []
self._server = util.tornado.CustomHTTPServer(self._tornado_app,
max_body_sizes=max_body_sizes,
default_max_body_size=self._settings.getInt(["server", "maxSize"]),
xheaders=True,
trusted_downstream=trusted_downstream)
self._server.listen(self._port, address=self._host if self._host != "::" else None) # special case - tornado
# only listens on v4 & v6
# if we use None as address
### From now on it's ok to launch subprocesses again
@@ -664,7 +686,8 @@ class Server(object):
# prepare our after startup function
def on_after_startup():
self._logger.info("Listening on http://%s:%d" % (self._host, self._port))
self._logger.info("Listening on http://{}:{}".format(self._host if not ":" in self._host else "[" + self._host + "]",
self._port))
if safe_mode and self._settings.getBoolean(["server", "startOnceInSafeMode"]):
self._logger.info("Server started successfully in safe mode as requested from config, removing flag")
@@ -785,7 +808,8 @@ class Server(object):
timer.start()
def _setup_app(self, app):
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, OctoPrintFlaskResponse, OctoPrintJsonEncoder
from octoprint.server.util.flask import ReverseProxiedEnvironment, OctoPrintFlaskRequest, \
OctoPrintFlaskResponse, OctoPrintJsonEncoder, OctoPrintSessionInterface
s = settings()
@@ -820,6 +844,7 @@ class Server(object):
OctoPrintFlaskRequest.environment_wrapper = reverse_proxied
app.request_class = OctoPrintFlaskRequest
app.response_class = OctoPrintFlaskResponse
app.session_interface = OctoPrintSessionInterface()
@app.before_request
def before_request():
@@ -1315,25 +1340,13 @@ class Server(object):
js_filters = ["sourcemap_remove", "js_delimiter_bundler"]
js_plugin_filters = ["sourcemap_remove", "js_delimiter_bundler"]
if self._settings.getBoolean(["feature", "legacyPluginAssets"]):
# TODO remove again in 1.3.8
def js_bundles_for_plugins(collection, filters=None):
"""Produces Bundle instances"""
result = OrderedDict()
for plugin, assets in collection.items():
if len(assets):
result[plugin] = Bundle(*assets, filters=filters)
return result
else:
def js_bundles_for_plugins(collection, filters=None):
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
result = OrderedDict()
for plugin, assets in collection.items():
if len(assets):
result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)
return result
def js_bundles_for_plugins(collection, filters=None):
"""Produces JsPluginBundle instances that output IIFE wrapped assets"""
result = OrderedDict()
for plugin, assets in collection.items():
if len(assets):
result[plugin] = JsPluginBundle(plugin, *assets, filters=filters)
return result
js_core = dynamic_core_assets["js"] + \
all_assets_for_plugins(dynamic_plugin_assets["bundled"]["js"]) + \
@@ -1445,7 +1458,12 @@ class Server(object):
global loginManager
loginManager = LoginManager()
loginManager.session_protection = "strong"
# "strong" is incompatible to remember me, see maxcountryman/flask-login#156. It also causes issues with
# clients toggling between IPv4 and IPv6 client addresses due to names being resolved one way or the other as
# at least observed on a Win10 client targeting "localhost", resolved as both "127.0.0.1" and "::1"
loginManager.session_protection = "basic"
loginManager.user_callback = load_user
loginManager.unauthorized_callback = unauthorized_user
@@ -1459,25 +1477,25 @@ class Server(object):
loginManager.init_app(app, add_context_processor=False)
def _start_intermediary_server(self):
import BaseHTTPServer
import SimpleHTTPServer
try:
# noinspection PyCompatibility
from http.server import HTTPServer, BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import threading
import socket
host = self._host
port = self._port
if host is None:
host = self._settings.get(["server", "host"])
if port is None:
port = self._settings.getInt(["server", "port"])
self._logger.debug("Starting intermediary server on {}:{}".format(host, port))
class IntermediaryServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
class IntermediaryServerHandler(BaseHTTPRequestHandler):
def __init__(self, rules=None, *args, **kwargs):
if rules is None:
rules = []
self.rules = rules
SimpleHTTPServer.SimpleHTTPRequestHandler.__init__(self, *args, **kwargs)
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
def do_GET(self):
request_path = self.path
@@ -1527,9 +1545,27 @@ class Server(object):
rules = map(process, filter(lambda rule: len(rule) == 2 or len(rule) == 3, rules))
self._intermediary_server = BaseHTTPServer.HTTPServer((host, port),
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
bind_and_activate=False)
class HTTPServerV6(HTTPServer):
address_family = socket.AF_INET6
def __init__(self, *args, **kwargs):
HTTPServer.__init__(self, *args, **kwargs)
# make sure to enable dual stack mode, otherwise the socket might only listen on IPv6
self.socket.setsockopt(octoprint.util.net.IPPROTO_IPV6, octoprint.util.net.IPV6_V6ONLY, 0)
if ":" in host:
# v6
ServerClass = HTTPServerV6
else:
# v4
ServerClass = HTTPServer
self._logger.debug("Starting intermediary server on http://{}:{}".format(host if not ":" in host else "[" + host + "]", port))
self._intermediary_server = ServerClass((host, port),
lambda *args, **kwargs: IntermediaryServerHandler(rules, *args, **kwargs),
bind_and_activate=False)
# if possible, make sure our socket's port descriptor isn't handed over to subprocesses
from octoprint.util.platform import set_close_exec
+230 -157
View File
@@ -246,7 +246,7 @@ def _logout(user):
@api.route("/util/test", methods=["POST"])
@restricted_access
@admin_permission.require(403)
def utilTestPath():
def utilTest():
valid_commands = dict(
path=["path"],
url=["url"],
@@ -258,169 +258,242 @@ def utilTestPath():
return response
if command == "path":
import os
from octoprint.util.paths import normalize
path = normalize(data["path"])
if not path:
return jsonify(path=path, exists=False, typeok=False, access=False, result=False)
check_type = None
check_access = []
if "check_type" in data and data["check_type"] in ("file", "dir"):
check_type = data["check_type"]
if "check_access" in data:
request_check_access = data["check_access"]
if not isinstance(request_check_access, list):
request_check_access = list(request_check_access)
check_access = [check for check in request_check_access if check in ("r", "w", "x")]
exists = os.path.exists(path)
# check if path exists
type_mapping = dict(file=os.path.isfile, dir=os.path.isdir)
if check_type:
typeok = type_mapping[check_type](path)
else:
typeok = exists
# check if path allows requested access
access_mapping = dict(r=os.R_OK, w=os.W_OK, x=os.X_OK)
if check_access:
access = os.access(path, reduce(lambda x, y: x | y, map(lambda a: access_mapping[a], check_access)))
else:
access = exists
return jsonify(path=path, exists=exists, typeok=typeok, access=access, result=exists and typeok and access)
return _test_path(data)
elif command == "url":
import requests
class StatusCodeRange(object):
def __init__(self, start=None, end=None):
self.start = start
self.end = end
def __contains__(self, item):
if not isinstance(item, int):
return False
if self.start and self.end:
return self.start <= item < self.end
elif self.start:
return self.start <= item
elif self.end:
return item < self.end
else:
return False
def as_dict(self):
return dict(
start=self.start,
end=self.end
)
status_ranges = dict(
informational=StatusCodeRange(start=100,end=200),
success=StatusCodeRange(start=200,end=300),
redirection=StatusCodeRange(start=300,end=400),
client_error=StatusCodeRange(start=400,end=500),
server_error=StatusCodeRange(start=500,end=600),
normal=StatusCodeRange(end=400),
error=StatusCodeRange(start=400,end=600),
any=StatusCodeRange(start=100),
timeout=StatusCodeRange(start=0, end=1)
)
url = data["url"]
method = data.get("method", "HEAD")
timeout = 3.0
valid_ssl = True
check_status = [status_ranges["normal"]]
if "timeout" in data:
try:
timeout = float(data["timeout"])
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
if "validSsl" in data:
valid_ssl = data["validSsl"] in valid_boolean_trues
if "status" in data:
request_status = data["status"]
if not isinstance(request_status, list):
request_status = [request_status]
check_status = []
for rs in request_status:
if isinstance(rs, int):
check_status.append([rs])
else:
if rs in status_ranges:
check_status.append(status_ranges[rs])
else:
code = requests.codes[rs]
if code is not None:
check_status.append([code])
try:
response = requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl)
status = response.status_code
except:
status = 0
result = dict(
url=url,
status=status,
result=any(map(lambda x: status in x, check_status))
)
if "response" in data and (data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")):
import base64
content = base64.standard_b64encode(response.content)
if data["response"] == "json":
try:
content = response.json()
except:
logging.getLogger(__name__).exception("Couldn't convert response to json")
result["result"] = False
result["response"] = dict(
headers=dict(response.headers),
content=content
)
return jsonify(**result)
return _test_url(data)
elif command == "server":
host = data["host"]
try:
port = int(data["port"])
except:
return make_response("{!r} is not a valid value for port (must be int)".format(data["port"]), 400)
return _test_server(data)
timeout = 3.05
if "timeout" in data:
def _test_path(data):
import os
from octoprint.util.paths import normalize
path = normalize(data["path"], real=False)
if not path:
return jsonify(path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False)
unreal_path = path
path = os.path.realpath(path)
check_type = None
check_access = []
if "check_type" in data and data["check_type"] in ("file", "dir"):
check_type = data["check_type"]
if "check_access" in data:
request_check_access = data["check_access"]
if not isinstance(request_check_access, list):
request_check_access = list(request_check_access)
check_access = [check for check in request_check_access if check in ("r", "w", "x")]
allow_create_dir = data.get("allow_create_dir", False) and check_type == "dir"
check_writable_dir = data.get("check_writable_dir", False) and check_type == "dir"
if check_writable_dir and "w" not in check_access:
check_access.append("w")
# check if path exists
exists = os.path.exists(path)
if not exists:
if os.path.islink(unreal_path):
# broken symlink, see #2644
logging.getLogger(__name__).error("{} is a broken symlink pointing at non existing {}".format(unreal_path, path))
return jsonify(path=unreal_path, exists=False, typeok=False, broken_symlink=True, access=False, result=False)
elif check_type == "dir" and allow_create_dir:
try:
timeout = float(data["timeout"])
os.makedirs(path)
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]), 400)
logging.getLogger(__name__).exception("Error while trying to create {}".format(path))
return jsonify(path=path, exists=False, typeok=False, broken_symlink=False, access=False, result=False)
else:
exists = True
protocol = data.get("protocol", "tcp")
if protocol not in ("tcp", "udp"):
return make_response("{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), 400)
# check path type
type_mapping = dict(file=os.path.isfile, dir=os.path.isdir)
if check_type:
typeok = type_mapping[check_type](path)
else:
typeok = exists
from octoprint.util import server_reachable
reachable = server_reachable(host, port, timeout=timeout, proto=protocol)
# check if path allows requested access
access_mapping = dict(r=os.R_OK, w=os.W_OK, x=os.X_OK)
if check_access:
mode = 0
for a in map(lambda x: access_mapping[x], check_access):
mode |= a
access = os.access(path, mode)
else:
access = exists
result = dict(host=host,
port=port,
protocol=protocol,
result=reachable)
if check_writable_dir and check_type == "dir":
try:
test_path = os.path.join(path, ".testballoon.txt")
with open(test_path, "wb") as f:
f.write("Test")
os.remove(test_path)
except:
logging.getLogger(__name__).exception("Error while testing if {} is really writable".format(path))
return jsonify(path=path, exists=exists, typeok=typeok, broken_symlink=False, access=False, result=False)
return jsonify(**result)
return jsonify(path=path, exists=exists, typeok=typeok, broken_symlink=False, access=access, result=exists and typeok and access)
def _test_url(data):
import requests
class StatusCodeRange(object):
def __init__(self, start=None, end=None):
self.start = start
self.end = end
def __contains__(self, item):
if not isinstance(item, int):
return False
if self.start and self.end:
return self.start <= item < self.end
elif self.start:
return self.start <= item
elif self.end:
return item < self.end
else:
return False
def as_dict(self):
return dict(
start=self.start,
end=self.end
)
status_ranges = dict(
informational=StatusCodeRange(start=100, end=200),
success=StatusCodeRange(start=200, end=300),
redirection=StatusCodeRange(start=300, end=400),
client_error=StatusCodeRange(start=400, end=500),
server_error=StatusCodeRange(start=500, end=600),
normal=StatusCodeRange(end=400),
error=StatusCodeRange(start=400, end=600),
any=StatusCodeRange(start=100),
timeout=StatusCodeRange(start=0, end=1)
)
url = data["url"]
method = data.get("method", "HEAD")
timeout = 3.0
valid_ssl = True
check_status = [status_ranges["normal"]]
content_type_whitelist = None
content_type_blacklist = None
if "timeout" in data:
try:
timeout = float(data["timeout"])
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]),
400)
if "validSsl" in data:
valid_ssl = data["validSsl"] in valid_boolean_trues
if "status" in data:
request_status = data["status"]
if not isinstance(request_status, list):
request_status = [request_status]
check_status = []
for rs in request_status:
if isinstance(rs, int):
check_status.append([rs])
else:
if rs in status_ranges:
check_status.append(status_ranges[rs])
else:
code = requests.codes[rs]
if code is not None:
check_status.append([code])
if "content_type_whitelist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
return make_response("content_type_whitelist must be a list of mime types")
content_type_whitelist = map(util.parse_mime_type, data["content_type_whitelist"])
if "content_type_blacklist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
return make_response("content_type_blacklist must be a list of mime types")
content_type_blacklist = map(util.parse_mime_type, data["content_type_blacklist"])
response_result = None
outcome = True
status = 0
try:
with requests.request(method=method, url=url, timeout=timeout, verify=valid_ssl, stream=True) as response:
status = response.status_code
outcome = outcome and any(map(lambda x: status in x, check_status))
content_type = response.headers.get("content-type")
response_result = dict(headers=dict(response.headers),
content_type=content_type)
parsed_content_type = util.parse_mime_type(content_type)
in_whitelist = content_type_whitelist is None or any(
map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_whitelist))
in_blacklist = content_type_blacklist is not None and any(
map(lambda x: util.mime_type_matches(parsed_content_type, x), content_type_blacklist))
if not in_whitelist or in_blacklist:
# we don't support this content type
response.close()
outcome = False
elif "response" in data and (
data["response"] in valid_boolean_trues or data["response"] in ("json", "bytes")):
if data["response"] == "json":
content = response.json()
else:
import base64
content = base64.standard_b64encode(response.content)
response_result["content"] = content
except:
logging.getLogger(__name__).exception("Error while running a test {} request on {}".format(method, url))
outcome = False
result = dict(
url=url,
status=status,
result=outcome
)
if response_result:
result["response"] = response_result
return jsonify(**result)
def _test_server(data):
host = data["host"]
try:
port = int(data["port"])
except:
return make_response("{!r} is not a valid value for port (must be int)".format(data["port"]), 400)
timeout = 3.05
if "timeout" in data:
try:
timeout = float(data["timeout"])
except:
return make_response("{!r} is not a valid value for timeout (must be int or float)".format(data["timeout"]),
400)
protocol = data.get("protocol", "tcp")
if protocol not in ("tcp", "udp"):
return make_response("{!r} is not a valid value for protocol, must be tcp or udp".format(protocol), 400)
from octoprint.util import server_reachable
reachable = server_reachable(host, port, timeout=timeout, proto=protocol)
result = dict(host=host,
port=port,
protocol=protocol,
result=reachable)
return jsonify(**result)
+2 -2
View File
@@ -78,8 +78,8 @@ def _get_options():
default_profile = printerProfileManager.get_default()
options = dict(
ports=sorted(connection_options["ports"]),
baudrates=sorted(connection_options["baudrates"], reverse=True),
ports=connection_options["ports"],
baudrates=connection_options["baudrates"],
printerProfiles=[dict(id=printer_profile["id"], name=printer_profile["name"] if "name" in printer_profile else printer_profile["id"]) for printer_profile in profile_options.values() if "id" in printer_profile],
portPreference=connection_options["portPreference"],
baudratePreference=connection_options["baudratePreference"],
+19 -7
View File
@@ -9,7 +9,7 @@ from flask import request, jsonify, make_response, url_for
from octoprint.filemanager.destinations import FileDestinations
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT
from octoprint.server import printer, fileManager, slicingManager, eventManager, NO_CONTENT, current_user
from octoprint.server.util.flask import restricted_access, get_json_command_from_request, with_revalidation_checking
from octoprint.server.api import api
from octoprint.events import Events
@@ -102,7 +102,7 @@ def readGcodeFiles():
files = _getFileList(FileDestinations.LOCAL, filter=filter, recursive=recursive, allow_from_cache=not force)
files.extend(_getFileList(FileDestinations.SDCARD))
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False))
return jsonify(files=files, free=usage.free, total=usage.total)
@@ -125,7 +125,7 @@ def readGcodeFilesForOrigin(origin):
files = _getFileList(origin, filter=filter, recursive=recursive, allow_from_cache=not force)
if origin == FileDestinations.LOCAL:
usage = psutil.disk_usage(settings().getBaseFolder("uploads"))
usage = psutil.disk_usage(settings().getBaseFolder("uploads", check_writable=False))
return jsonify(files=files, free=usage.free, total=usage.total)
else:
return jsonify(files=files)
@@ -149,8 +149,16 @@ def _getFileList(origin, path=None, filter=None, recursive=False, allow_from_cac
files = []
if sdFileList is not None:
for sdFile, sdSize in sdFileList:
type_path = octoprint.filemanager.get_file_type(sdFile)
if not type_path:
# only supported extensions
continue
else:
file_type = type_path[0]
file = {
"type": "machinecode",
"type": file_type,
"typePath": type_path,
"name": sdFile,
"display": sdFile,
"path": sdFile,
@@ -316,6 +324,8 @@ def uploadGcodeFile(target):
reselect = printer.is_current_file(futureFullPathInStorage, sd)
user = current_user.get_name()
def fileProcessingFinished(filename, absFilename, destination):
"""
Callback for when the file processing (upload, optional slicing, addition to analysis queue) has
@@ -340,7 +350,7 @@ def uploadGcodeFile(target):
exact file is already selected, such reloading it.
"""
if octoprint.filemanager.valid_file_type(added_file, "gcode") and (selectAfterUpload or printAfterSelect or reselect):
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect)
printer.select_file(absFilename, destination == FileDestinations.SDCARD, printAfterSelect, user)
try:
added_file = fileManager.add_file(FileDestinations.LOCAL, futureFullPathInStorage, upload,
@@ -485,6 +495,8 @@ def gcodeFileCommand(filename, target):
if response is not None:
return response
user = current_user.get_name()
if command == "select":
if not _verifyFileExists(target, filename):
return make_response("File not found on '%s': %s" % (target, filename), 404)
@@ -505,7 +517,7 @@ def gcodeFileCommand(filename, target):
sd = True
else:
filenameToSelect = fileManager.path_on_disk(target, filename)
printer.select_file(filenameToSelect, sd, printAfterLoading)
printer.select_file(filenameToSelect, sd, printAfterLoading, user)
elif command == "slice":
if not _verifyFileExists(target, filename):
@@ -608,7 +620,7 @@ def gcodeFileCommand(filename, target):
sd = True
else:
filenameToSelect = fileManager.path_on_disk(target, path)
printer.select_file(filenameToSelect, sd, print_after_slicing)
printer.select_file(filenameToSelect, sd, print_after_slicing, user)
try:
fileManager.slice(slicer, target, filename, target, full_path,
+5 -3
View File
@@ -7,7 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from flask import request, make_response, jsonify
from octoprint.server import printer, NO_CONTENT
from octoprint.server import printer, NO_CONTENT, current_user
from octoprint.server.util.flask import restricted_access, get_json_command_from_request
from octoprint.server.api import api
import octoprint.util as util
@@ -34,14 +34,16 @@ def controlJob():
tags = {"source:api", "api:job"}
user = current_user.get_name()
if command == "start":
if activePrintjob:
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
printer.start_print(tags=tags)
printer.start_print(tags=tags, user=user)
elif command == "restart":
if not printer.is_paused():
return make_response("Printer does not have an active print job or is not paused", 409)
printer.start_print(tags=tags)
printer.start_print(tags=tags, user=user)
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
+1 -1
View File
@@ -32,7 +32,7 @@ from flask_babel import Locale
@restricted_access
@admin_permission.require(403)
def getInstalledLanguagePacks():
translation_folder = settings().getBaseFolder("translations")
translation_folder = settings().getBaseFolder("translations", check_writable=False)
if not os.path.exists(translation_folder):
return jsonify(language_packs=dict(_core=[]))
+72 -22
View File
@@ -14,7 +14,7 @@ from werkzeug.exceptions import BadRequest
from octoprint.events import eventManager, Events
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission, printer
from octoprint.server import admin_permission, printer, pluginManager
from octoprint.server.api import api, NO_CONTENT
from octoprint.server.util.flask import restricted_access, with_revalidation_checking
@@ -122,8 +122,7 @@ def getSettings():
"modelSizeDetection": s.getBoolean(["feature", "modelSizeDetection"]),
"printCancelConfirmation": s.getBoolean(["feature", "printCancelConfirmation"]),
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
"legacyPluginAssets": s.getBoolean(["feature", "legacyPluginAssets"])
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"])
},
"serial": {
"port": connectionOptions["portPreference"],
@@ -140,6 +139,8 @@ def getSettings():
"timeoutTemperatureAutoreport": s.getFloat(["serial", "timeout", "temperatureAutoreport"]),
"timeoutSdStatus": s.getFloat(["serial", "timeout", "sdStatus"]),
"timeoutSdStatusAutoreport": s.getFloat(["serial", "timeout", "sdStatusAutoreport"]),
"timeoutBaudrateDetectionPause": s.getFloat(["serial", "timeout", "baudrateDetectionPause"]),
"timeoutPositionLogWait": s.getFloat(["serial", "timeout", "positionLogWait"]),
"log": s.getBoolean(["serial", "log"]),
"additionalPorts": s.get(["serial", "additionalPorts"]),
"additionalBaudrates": s.get(["serial", "additionalBaudrates"]),
@@ -149,6 +150,7 @@ def getSettings():
"ignoreErrorsFromFirmware": s.getBoolean(["serial", "ignoreErrorsFromFirmware"]),
"disconnectOnErrors": s.getBoolean(["serial", "disconnectOnErrors"]),
"triggerOkForM29": s.getBoolean(["serial", "triggerOkForM29"]),
"blockM0M1": s.getBoolean(["serial", "blockM0M1"]),
"logPositionOnPause": s.getBoolean(["serial", "logPositionOnPause"]),
"logPositionOnCancel": s.getBoolean(["serial", "logPositionOnCancel"]),
"supportResendsWithoutOk": s.get(["serial", "supportResendsWithoutOk"]),
@@ -289,7 +291,9 @@ def setSettings():
return make_response("Malformed request, need settings dictionary, "
"got a {} instead: {!r}".format(type(data).__name__, data), 400)
_saveSettings(data)
response = _saveSettings(data)
if response:
return response
return getSettings()
@@ -308,6 +312,38 @@ def deleteApiKey():
settings().deleteApiKey()
return NO_CONTENT
@api.route("/settings/templates", methods=["GET"])
@restricted_access
@admin_permission.require(403)
def fetchTemplateData():
from octoprint.server.views import fetch_template_data
refresh = request.values.get("refresh", "false") in valid_boolean_trues
templates, _, _ = fetch_template_data(refresh=refresh)
result = dict()
for tt in templates:
result[tt] = []
for key in templates[tt]["order"]:
entry = templates[tt]["entries"].get(key)
if not entry:
continue
if isinstance(entry, dict):
name = key
else:
name, entry = entry
data = dict(id=key, name=name)
if entry and "_plugin" in entry:
plugin = pluginManager.get_plugin_info(entry["_plugin"], require_enabled=False)
data["plugin_id"] = plugin.key
data["plugin_name"] = plugin.name
result[tt].append(data)
return jsonify(order=result)
def _saveSettings(data):
logger = logging.getLogger(__name__)
@@ -317,6 +353,16 @@ def _saveSettings(data):
# NOTE: Remember to adjust the docs of the data model on the Settings API if anything
# is changed, added or removed here
if "folder" in data.keys():
try:
if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
except IOError:
return make_response("One of the configured folders is invalid", 400)
if "api" in data.keys():
if "enabled" in data["api"]: s.setBoolean(["api", "enabled"], data["api"]["enabled"])
if "allowCrossOrigin" in data["api"]: s.setBoolean(["api", "allowCrossOrigin"], data["api"]["allowCrossOrigin"])
@@ -357,22 +403,23 @@ def _saveSettings(data):
if "modelSizeDetection" in data["feature"]: s.setBoolean(["feature", "modelSizeDetection"], data["feature"]["modelSizeDetection"])
if "printCancelConfirmation" in data["feature"]: s.setBoolean(["feature", "printCancelConfirmation"], data["feature"]["printCancelConfirmation"])
if "g90InfluencesExtruder" in data["feature"]: s.setBoolean(["feature", "g90InfluencesExtruder"], data["feature"]["g90InfluencesExtruder"])
if "legacyPluginAssets" in data["feature"]: s.setBoolean(["feature", "legacyPluginAssets"], data["feature"]["legacyPluginAssets"])
if "autoUppercaseBlacklist" in data["feature"] and isinstance(data["feature"]["autoUppercaseBlacklist"], (list, tuple)): s.set(["feature", "autoUppercaseBlacklist"], data["feature"]["autoUppercaseBlacklist"])
if "serial" in data.keys():
if "autoconnect" in data["serial"]: s.setBoolean(["serial", "autoconnect"], data["serial"]["autoconnect"])
if "port" in data["serial"]: s.set(["serial", "port"], data["serial"]["port"])
if "baudrate" in data["serial"]: s.setInt(["serial", "baudrate"], data["serial"]["baudrate"])
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"])
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"])
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"])
if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"])
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"])
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"])
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"])
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"])
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"])
if "timeoutConnection" in data["serial"]: s.setFloat(["serial", "timeout", "connection"], data["serial"]["timeoutConnection"], minimum=1.0)
if "timeoutDetection" in data["serial"]: s.setFloat(["serial", "timeout", "detection"], data["serial"]["timeoutDetection"], minimum=1.0)
if "timeoutCommunication" in data["serial"]: s.setFloat(["serial", "timeout", "communication"], data["serial"]["timeoutCommunication"], minimum=1.0)
if "timeoutCommunicationBusy" in data["serial"]: s.setFloat(["serial", "timeout", "communicationBusy"], data["serial"]["timeoutCommunicationBusy"], minimum=1.0)
if "timeoutTemperature" in data["serial"]: s.setFloat(["serial", "timeout", "temperature"], data["serial"]["timeoutTemperature"], minimum=1.0)
if "timeoutTemperatureTargetSet" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureTargetSet"], data["serial"]["timeoutTemperatureTargetSet"], minimum=1.0)
if "timeoutTemperatureAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "temperatureAutoreport"], data["serial"]["timeoutTemperatureAutoreport"], minimum=0.0)
if "timeoutSdStatus" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatus"], data["serial"]["timeoutSdStatus"], minimum=1.0)
if "timeoutSdStatusAutoreport" in data["serial"]: s.setFloat(["serial", "timeout", "sdStatusAutoreport"], data["serial"]["timeoutSdStatusAutoreport"], minimum=0.0)
if "timeoutBaudrateDetectionPause" in data["serial"]: s.setFloat(["serial", "timeout", "baudrateDetectionPause"], data["serial"]["timeoutBaudrateDetectionPause"], minimum=0.0)
if "timeoutPositionLogWait" in data["serial"]: s.setFloat(["serial", "timeout", "positionLogWait"], data["serial"]["timeoutPositionLogWait"], minimum=1.0)
if "additionalPorts" in data["serial"] and isinstance(data["serial"]["additionalPorts"], (list, tuple)): s.set(["serial", "additionalPorts"], data["serial"]["additionalPorts"])
if "additionalBaudrates" in data["serial"] and isinstance(data["serial"]["additionalBaudrates"], (list, tuple)): s.set(["serial", "additionalBaudrates"], data["serial"]["additionalBaudrates"])
if "longRunningCommands" in data["serial"] and isinstance(data["serial"]["longRunningCommands"], (list, tuple)): s.set(["serial", "longRunningCommands"], data["serial"]["longRunningCommands"])
@@ -381,6 +428,7 @@ def _saveSettings(data):
if "ignoreErrorsFromFirmware" in data["serial"]: s.setBoolean(["serial", "ignoreErrorsFromFirmware"], data["serial"]["ignoreErrorsFromFirmware"])
if "disconnectOnErrors" in data["serial"]: s.setBoolean(["serial", "disconnectOnErrors"], data["serial"]["disconnectOnErrors"])
if "triggerOkForM29" in data["serial"]: s.setBoolean(["serial", "triggerOkForM29"], data["serial"]["triggerOkForM29"])
if "blockM0M1" in data["serial"]: s.setBoolean(["serial", "blockM0M1"], data["serial"]["blockM0M1"])
if "supportResendsWithoutOk" in data["serial"]:
value = data["serial"]["supportResendsWithoutOk"]
if value in ("always", "detect", "never"):
@@ -416,15 +464,17 @@ def _saveSettings(data):
logging.getLogger("SERIAL").setLevel(logging.DEBUG)
logging.getLogger("SERIAL").debug("Enabling serial logging")
if "folder" in data.keys():
if "uploads" in data["folder"]: s.setBaseFolder("uploads", data["folder"]["uploads"])
if "timelapse" in data["folder"]: s.setBaseFolder("timelapse", data["folder"]["timelapse"])
if "timelapseTmp" in data["folder"]: s.setBaseFolder("timelapse_tmp", data["folder"]["timelapseTmp"])
if "logs" in data["folder"]: s.setBaseFolder("logs", data["folder"]["logs"])
if "watched" in data["folder"]: s.setBaseFolder("watched", data["folder"]["watched"])
if "temperature" in data.keys():
if "profiles" in data["temperature"]: s.set(["temperature", "profiles"], data["temperature"]["profiles"])
if "profiles" in data["temperature"]:
result = []
for profile in data["temperature"]["profiles"]:
try:
profile["bed"] = int(profile["bed"])
profile["extruder"] = int(profile["extruder"])
except ValueError:
pass
result.append(profile)
s.set(["temperature", "profiles"], result)
if "cutoff" in data["temperature"]:
try:
cutoff = int(data["temperature"]["cutoff"])
+2
View File
@@ -75,6 +75,8 @@ def loginFromApiKeyRequestHandler():
if not loginUser(user):
return _flask.make_response("Invalid API key", 403)
_flask.g.login_via_apikey = True
def loginFromAuthorizationHeaderRequestHandler():
"""
+8
View File
@@ -498,6 +498,14 @@ class OctoPrintFlaskResponse(flask.Response):
flask.Response.set_cookie(self, key, expires=0, max_age=0, path=path, domain=domain)
class OctoPrintSessionInterface(flask.sessions.SecureCookieSessionInterface):
def save_session(self, app, session, response):
if flask.g.get("login_via_apikey", False):
return
return super(OctoPrintSessionInterface, self).save_session(app, session, response)
#~~ passive login helper
def passive_login():
+12 -12
View File
@@ -7,10 +7,10 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import threading
import sockjs.tornado
import sockjs.tornado.session
import sockjs.tornado.proto
import sockjs.tornado.util
import octoprint.vendor.sockjs.tornado
import octoprint.vendor.sockjs.tornado.session
import octoprint.vendor.sockjs.tornado.proto
import octoprint.vendor.sockjs.tornado.util
import time
import octoprint.timelapse
@@ -28,9 +28,9 @@ import wrapt
import json
class ThreadSafeSession(sockjs.tornado.session.Session):
class ThreadSafeSession(octoprint.vendor.sockjs.tornado.session.Session):
def __init__(self, conn, server, session_id, expiry=None):
sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
octoprint.vendor.sockjs.tornado.session.Session.__init__(self, conn, server, session_id, expiry=expiry)
def set_handler(self, handler, start_heartbeat=True):
if getattr(handler, "__orig_send_pack", None) is None:
@@ -44,10 +44,10 @@ class ThreadSafeSession(sockjs.tornado.session.Session):
handler.send_pack = send_pack
setattr(handler, "__orig_send_pack", orig_send_pack)
return sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
return octoprint.vendor.sockjs.tornado.session.Session.set_handler(self, handler, start_heartbeat=start_heartbeat)
def remove_handler(self, handler):
result = sockjs.tornado.session.Session.remove_handler(self, handler)
result = octoprint.vendor.sockjs.tornado.session.Session.remove_handler(self, handler)
if getattr(handler, "__orig_send_pack", None) is not None:
handler.send_pack = getattr(handler, "__orig_send_pack")
@@ -58,18 +58,18 @@ class ThreadSafeSession(sockjs.tornado.session.Session):
class JsonEncodingSessionWrapper(wrapt.ObjectProxy):
def send_message(self, msg, stats=True, binary=False):
self.send_jsonified(json.dumps(sockjs.tornado.util.bytes_to_str(msg),
self.send_jsonified(json.dumps(octoprint.vendor.sockjs.tornado.util.bytes_to_str(msg),
separators=(',', ':'),
default=JsonEncoding.encode),
stats)
class PrinterStateConnection(sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
class PrinterStateConnection(octoprint.vendor.sockjs.tornado.SockJSConnection, octoprint.printer.PrinterCallback):
def __init__(self, printer, fileManager, analysisQueue, userManager, eventManager, pluginManager, session):
if isinstance(session, sockjs.tornado.session.Session):
if isinstance(session, octoprint.vendor.sockjs.tornado.session.Session):
session = JsonEncodingSessionWrapper(session)
sockjs.tornado.SockJSConnection.__init__(self, session)
octoprint.vendor.sockjs.tornado.SockJSConnection.__init__(self, session)
self._logger = logging.getLogger(__name__)
+69 -89
View File
@@ -7,11 +7,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
import os
import datetime
import stat
import mimetypes
import email
import time
import re
import tornado
@@ -29,35 +25,6 @@ import tornado.util
import octoprint.util
#~~ Monkey patching
def fix_ioloop_scheduling():
"""
This monkey patches tornado's :meth:``tornado.ioloop.PeriodicCallback._schedule_next`` method so it no longer
blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to
the first ever contact to an NTP server).
Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290
"""
import math
# patched implementation taken from PR
def _schedule_next(self):
if self._running:
current_time = self.io_loop.time()
if self._next_timeout <= current_time:
callback_time_sec = self.callback_time / 1000.0
self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec
self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)
# replace original implementation with patched version
import tornado.ioloop
tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next
def fix_json_encode():
"""
@@ -610,7 +577,8 @@ class WsgiInputContainer(object):
if not data:
raise Exception("WSGI app did not call start_response")
status_code = int(data["status"].split()[0])
status_code, reason = data["status"].split(" ", 1)
status_code = int(status_code)
headers = data["headers"]
header_set = set(k.lower() for (k, v) in headers)
body = tornado.escape.utf8(body)
@@ -628,13 +596,12 @@ class WsgiInputContainer(object):
headers.append((header, value))
headers = [(header, value) for header, value in headers if not header.lower() in self.removed_headers]
parts = [tornado.escape.utf8("HTTP/1.1 " + data["status"] + "\r\n")]
start_line = tornado.httputil.ResponseStartLine("HTTP/1.1", status_code, reason)
header_obj = tornado.httputil.HTTPHeaders()
for key, value in headers:
parts.append(tornado.escape.utf8(key) + b": " + tornado.escape.utf8(value) + b"\r\n")
parts.append(b"\r\n")
parts.append(body)
request.write(b"".join(parts))
request.finish()
header_obj.add(key, value)
request.connection.write_headers(start_line, header_obj, chunk=body)
request.connection.finish()
self._log(status_code, request)
@staticmethod
@@ -669,22 +636,22 @@ class WsgiInputContainer(object):
host = request.host
port = 443 if request.protocol == "https" else 80
environ = {
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": "",
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
request.path, encoding=None, plus=False)),
"QUERY_STRING": request.query,
"REMOTE_ADDR": request.remote_ip,
"SERVER_NAME": host,
"SERVER_PORT": str(port),
"SERVER_PROTOCOL": request.version,
"wsgi.version": (1, 0),
"wsgi.url_scheme": request.protocol,
"wsgi.input": request_body,
"wsgi.errors": sys.stderr,
"wsgi.multithread": False,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
"REQUEST_METHOD": request.method,
"SCRIPT_NAME": "",
"PATH_INFO": to_wsgi_str(tornado.escape.url_unescape(
request.path, encoding=None, plus=False)),
"QUERY_STRING": request.query,
"REMOTE_ADDR": request.remote_ip,
"SERVER_NAME": host,
"SERVER_PORT": str(port),
"SERVER_PROTOCOL": request.version,
"wsgi.version": (1, 0),
"wsgi.url_scheme": request.protocol,
"wsgi.input": request_body,
"wsgi.errors": sys.stderr,
"wsgi.multithread": False,
"wsgi.multiprocess": True,
"wsgi.run_once": False,
}
if "Content-Type" in request.headers:
environ["CONTENT_TYPE"] = request.headers.pop("Content-Type")
@@ -705,7 +672,7 @@ class WsgiInputContainer(object):
log_method = access_log.error
request_time = 1000.0 * request.request_time()
summary = request.method + " " + request.uri + " (" + \
request.remote_ip + ")"
request.remote_ip + ")"
log_method("%d %s %.2fms", status_code, summary, request_time)
@@ -728,36 +695,25 @@ class CustomHTTPServer(tornado.httpserver.HTTPServer):
``default_max_body_size`` is the default maximum body size to apply if no specific one from ``max_body_sizes`` matches.
"""
def __init__(self, *args, **kwargs):
pass
def __init__(self, request_callback, no_keep_alive=False, io_loop=None,
xheaders=False, ssl_options=None, protocol=None,
decompress_request=False,
chunk_size=None, max_header_size=None,
idle_connection_timeout=None, body_timeout=None,
max_body_sizes=None, default_max_body_size=None, max_buffer_size=None):
self.request_callback = request_callback
self.no_keep_alive = no_keep_alive
self.xheaders = xheaders
self.protocol = protocol
self.conn_params = CustomHTTP1ConnectionParameters(
decompress=decompress_request,
chunk_size=chunk_size,
max_header_size=max_header_size,
header_timeout=idle_connection_timeout or 3600,
max_body_sizes=max_body_sizes,
default_max_body_size=default_max_body_size,
body_timeout=body_timeout)
tornado.tcpserver.TCPServer.__init__(self, io_loop=io_loop, ssl_options=ssl_options,
max_buffer_size=max_buffer_size,
read_chunk_size=chunk_size)
self._connections = set()
def initialize(self, *args, **kwargs):
default_max_body_size = kwargs.pop("default_max_body_size", None)
max_body_sizes = kwargs.pop("max_body_sizes", None)
tornado.httpserver.HTTPServer.initialize(self, *args, **kwargs)
additional = dict(default_max_body_size=default_max_body_size,
max_body_sizes=max_body_sizes)
self.conn_params = CustomHTTP1ConnectionParameters.from_stock_params(self.conn_params, **additional)
def handle_stream(self, stream, address):
context = tornado.httpserver._HTTPRequestContext(stream, address,
self.protocol)
conn = CustomHTTP1ServerConnection(
stream, self.conn_params, context)
self.protocol,
self.trusted_downstream)
conn = CustomHTTP1ServerConnection(stream, self.conn_params, context)
self._connections.add(conn)
conn.start_serving(self)
@@ -774,7 +730,7 @@ class CustomHTTP1ServerConnection(tornado.http1connection.HTTP1ServerConnection)
try:
while True:
conn = CustomHTTP1Connection(self.stream, False,
self.params, self.context)
self.params, self.context)
request_delegate = delegate.start_request(self, conn)
try:
ret = yield conn.read_response(request_delegate)
@@ -803,6 +759,9 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
"""
def __init__(self, stream, is_client, params=None, context=None):
if params is None:
params = CustomHTTP1ConnectionParameters()
tornado.http1connection.HTTP1Connection.__init__(self, stream, is_client, params=params, context=context)
import re
@@ -818,8 +777,13 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
current request exceeds the individual max content length, the request processing is aborted and an
``HTTPInputError`` is raised.
"""
content_length = headers.get("Content-Length")
if "Content-Length" in headers:
if "Transfer-Encoding" in headers:
# Response cannot contain both Content-Length and
# Transfer-Encoding headers.
# http://tools.ietf.org/html/rfc7230#section-3.3.3
raise tornado.httputil.HTTPInputError(
"Response with both Transfer-Encoding and Content-Length")
if "," in headers["Content-Length"]:
# Proxies sometimes cause Content-Length headers to get
# duplicated. If all the values are identical then we can
@@ -830,9 +794,14 @@ class CustomHTTP1Connection(tornado.http1connection.HTTP1Connection):
"Multiple unequal Content-Lengths: %r" %
headers["Content-Length"])
headers["Content-Length"] = pieces[0]
content_length = int(headers["Content-Length"])
content_length = int(content_length)
try:
content_length = int(headers["Content-Length"])
except ValueError:
# Handles non-integer Content-Length value.
raise tornado.httputil.HTTPInputError(
"Only integer Content-Length is allowed: %s" % headers["Content-Length"])
max_content_length = self._get_max_content_length(self._request_start_line.method, self._request_start_line.path)
if max_content_length is not None and 0 <= max_content_length < content_length:
raise tornado.httputil.HTTPInputError("Content-Length too long")
@@ -884,9 +853,20 @@ class CustomHTTP1ConnectionParameters(tornado.http1connection.HTTP1ConnectionPar
"""
def __init__(self, *args, **kwargs):
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, args, kwargs)
self.max_body_sizes = kwargs["max_body_sizes"] if "max_body_sizes" in kwargs else list()
self.default_max_body_size = kwargs["default_max_body_size"] if "default_max_body_size" in kwargs else None
max_body_sizes = kwargs.pop("max_body_sizes", list())
default_max_body_size = kwargs.pop("default_max_body_size", None)
tornado.http1connection.HTTP1ConnectionParameters.__init__(self, *args, **kwargs)
self.max_body_sizes = max_body_sizes
self.default_max_body_size = default_max_body_size
@classmethod
def from_stock_params(cls, other, **additional):
kwargs = dict(other.__dict__)
for key, value in additional.items():
kwargs[key] = value
return cls(**kwargs)
#~~ customized large response handler
+15 -3
View File
@@ -71,16 +71,28 @@ class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
def on_created(self, event):
thread = threading.Thread(target=self._repeatedly_check, args=(event.src_path,))
path = event.src_path
if octoprint.util.is_hidden_path(path):
return
thread = threading.Thread(target=self._repeatedly_check, args=(path,))
thread.daemon = True
thread.start()
def _repeatedly_check(self, path, interval=1, stable=5):
last_size = os.stat(path).st_size
try:
last_size = os.stat(path).st_size
except:
return
countdown = stable
while True:
new_size = os.stat(path).st_size
try:
new_size = os.stat(path).st_size
except:
return
if new_size == last_size:
self._logger.debug("File at {} is no longer growing, counting down: {}".format(path, countdown))
countdown -= 1
+16 -4
View File
@@ -173,8 +173,7 @@ def index():
force_refresh = util.flask.cache_check_headers() or "_refresh" in request.values or wizard_active(_templates.get(locale))
# if we need to refresh our template cache or it's not yet set, process it
if force_refresh or _templates.get(locale) is None or _plugin_names is None or _plugin_vars is None:
_templates[locale], _plugin_names, _plugin_vars = _process_templates()
fetch_template_data(refresh=force_refresh)
now = datetime.datetime.utcnow()
@@ -441,7 +440,14 @@ def _get_render_kwargs(templates, plugin_names, plugin_vars, now):
return render_kwargs
def _process_templates():
def fetch_template_data(refresh=False):
global _templates, _plugin_names, _plugin_vars
locale = g.locale.language if g.locale else "en"
if not refresh and _templates.get(locale) is not None and _plugin_names is not None and _plugin_vars is not None:
return _templates[locale], _plugin_names, _plugin_vars
first_run = settings().getBoolean(["server", "firstRun"])
##~~ prepare templates
@@ -741,6 +747,10 @@ def _process_templates():
templates[t]["entries"].update(template_sorting[t]["custom_insert_entries"](sorted_missing))
templates[t]["order"] = template_sorting[t]["custom_insert_order"](templates[t]["order"], sorted_missing)
_templates[locale] = templates
_plugin_names = plugin_names
_plugin_vars = plugin_vars
return templates, plugin_names, plugin_vars
@@ -828,6 +838,8 @@ def _process_template_config(name, implementation, rule, config=None, counter=1)
if "suffix" in data:
data["_key"] += data["suffix"]
data["_plugin"] = name
return data
@@ -946,7 +958,7 @@ def _get_all_translationfiles(locale, domain):
po_files = []
user_base_path = os.path.join(settings().getBaseFolder("translations"))
user_base_path = os.path.join(settings().getBaseFolder("translations", check_writable=False))
user_plugin_path = os.path.join(user_base_path, "_plugins")
# plugin translations
+155 -33
View File
@@ -91,7 +91,7 @@ default_settings = {
"autoconnect": False,
"log": False,
"timeout": {
"detection": 0.5,
"detection": 1,
"connection": 10,
"communication": 30,
"communicationBusy": 3,
@@ -100,7 +100,9 @@ default_settings = {
"temperatureAutoreport": 2,
"sdStatus": 1,
"sdStatusAutoreport": 1,
"resendOk": .5
"resendOk": .5,
"baudrateDetectionPause": 1.0,
"positionLogWait": 10.0,
},
"maxCommunicationTimeouts": {
"idle": 2,
@@ -118,7 +120,7 @@ default_settings = {
"logResends": True,
"supportResendsWithoutOk": "detect",
"logPositionOnPause": True,
"logPositionOnCancel": True,
"logPositionOnCancel": False,
"waitForStartOnConnect": False,
"alwaysSendChecksum": False,
"neverSendChecksum": False,
@@ -143,10 +145,11 @@ default_settings = {
},
# command specific flags
"triggerOkForM29": True
"triggerOkForM29": True,
"blockM0M1": True
},
"server": {
"host": "0.0.0.0",
"host": None,
"port": 5000,
"firstRun": True,
"startOnceInSafeMode": False,
@@ -163,7 +166,8 @@ default_settings = {
"schemeFallback": None,
"hostFallback": None,
"serverFallback": None,
"portFallback": None
"portFallback": None,
"trustedDownstream": []
},
"uploads": {
"maxSize": 1 * 1024 * 1024 * 1024, # 1GB
@@ -236,9 +240,8 @@ default_settings = {
"pollWatched": False,
"modelSizeDetection": True,
"printCancelConfirmation": True,
"autoUppercaseBlacklist": ["M117"],
"g90InfluencesExtruder": False,
"legacyPluginAssets": False # TODO remove again in 1.3.8
"autoUppercaseBlacklist": ["M117", "M118"],
"g90InfluencesExtruder": False
},
"folder": {
"uploads": None,
@@ -379,7 +382,6 @@ default_settings = {
"includeFilenameInOpened": True,
"hasBed": True,
"repetierStyleTargetTemperature": False,
"repetierStyleResends": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"reprapfwM114": False,
@@ -402,12 +404,13 @@ default_settings = {
"resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME: {firmware_name} PROTOCOL_VERSION:1.0",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": False,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
@@ -618,6 +621,8 @@ class Settings(object):
self._script_env = self._init_script_templating()
self.sanity_check_folders(folders=["logs", ])
def _init_basedir(self, basedir):
if basedir is not None:
self._basedir = basedir
@@ -625,7 +630,18 @@ class Settings(object):
self._basedir = _default_basedir(_APPNAME)
if not os.path.isdir(self._basedir):
os.makedirs(self._basedir)
try:
os.makedirs(self._basedir)
except:
self._logger.fatal("Could not create basefolder at {}. This is a fatal error, OctoPrint "
"can't run without a writable base folder.".format(self._basedir), exc_info=1)
raise
def sanity_check_folders(self, folders=None):
if folders is None:
folders = default_settings["folder"].keys()
for folder in folders:
self.getBaseFolder(folder, check_writable=True, deep_check_writable=True, log_error=True)
def _get_default_folder(self, type):
folder = default_settings["folder"][type]
@@ -919,7 +935,8 @@ class Settings(object):
self._migrate_gcode_scripts,
self._migrate_core_system_commands,
self._migrate_serial_features,
self._migrate_resend_without_ok
self._migrate_resend_without_ok,
self._migrate_string_temperature_profile_values
)
for migrate in migrators:
@@ -931,6 +948,8 @@ class Settings(object):
def _migrate_gcode_scripts(self, config):
"""
Migrates an old development version of gcode scripts to the new template based format.
Added in 1.2.0
"""
dirty = False
@@ -955,6 +974,8 @@ class Settings(object):
def _migrate_printer_parameters(self, config):
"""
Migrates the old "printer > parameters" data structure to the new printer profile mechanism.
Added in 1.2.0
"""
default_profile = config["printerProfiles"]["defaultProfile"] if "printerProfiles" in config and "defaultProfile" in config["printerProfiles"] else dict()
dirty = False
@@ -1020,6 +1041,8 @@ class Settings(object):
"""
Migrates the old "server > baseUrl" and "server > scheme" configuration entries to
"server > reverseProxy > prefixFallback" and "server > reverseProxy > schemeFallback".
Added in 1.2.0
"""
if "server" in config.keys() and ("baseUrl" in config["server"] or "scheme" in config["server"]):
prefix = ""
@@ -1047,6 +1070,8 @@ class Settings(object):
"""
Migrates the old event configuration format of type "events > gcodeCommandTrigger" and
"event > systemCommandTrigger" to the new events format.
Added in 1.2.0
"""
if "events" in config.keys() and ("gcodeCommandTrigger" in config["events"] or "systemCommandTrigger" in config["events"]):
self._logger.info("Migrating config (event subscriptions)...")
@@ -1142,6 +1167,8 @@ class Settings(object):
If server commands for action is not yet set, migrates command. Otherwise only
deletes definition from custom system commands.
Added in 1.3.0
"""
changed = False
@@ -1188,6 +1215,8 @@ class Settings(object):
Migrates feature flags identified as serial specific from the feature to the serial config tree and vice versa.
If a flag already exists in the target tree, only deletes the copy in the source tree.
Added in 1.3.7
"""
changed = False
@@ -1231,6 +1260,8 @@ class Settings(object):
Migrates supportResendsWithoutOk flag from boolean to ("always", "detect", "never") value range.
True gets migrated to "always", False to "detect" (which is the new default).
Added in 1.3.7
"""
if "serial" in config and "supportResendsWithoutOk" in config["serial"] \
and config["serial"]["supportResendsWithoutOk"] not in ("always", "detect", "never"):
@@ -1242,6 +1273,28 @@ class Settings(object):
return True
return False
def _migrate_string_temperature_profile_values(self, config):
"""
Migrates/fixes temperature profile wrongly saved with strings instead of ints as temperature values.
Added in 1.3.8
"""
if "temperature" in config and "profiles" in config["temperature"]:
profiles = config["temperature"]["profiles"]
if any(map(lambda x: not isinstance(x.get("extruder", 0), int) or not isinstance(x.get("bed", 0), int),
profiles)):
result = []
for profile in profiles:
try:
profile["extruder"] = int(profile["extruder"])
profile["bed"] = int(profile["bed"])
except ValueError:
pass
result.append(profile)
config["temperature"]["profiles"] = result
return True
return False
def backup(self, suffix, path=None):
import shutil
@@ -1371,17 +1424,22 @@ class Settings(object):
#~~ getter
def get(self, path, **kwargs):
error_on_path = kwargs.get("error_on_path", False)
new_kwargs = dict(kwargs)
if "error_on_path" in new_kwargs:
del new_kwargs["error_on_path"]
error_on_path = kwargs.pop("error_on_path", False)
validator = kwargs.pop("validator", None)
fallback = kwargs.pop("fallback", None)
try:
return self._get_value(path, **new_kwargs)
except NoSuchSettingsPath:
if error_on_path:
raise
return None
def process():
try:
return self._get_value(path, **kwargs)
except NoSuchSettingsPath:
if error_on_path:
raise
return None
result = process()
if callable(validator) and not validator(result):
result = fallback
return result
def getInt(self, path, **kwargs):
minimum = kwargs.pop("min", None)
@@ -1437,7 +1495,7 @@ class Settings(object):
return value.lower() in valid_boolean_trues
return value is not None
def getBaseFolder(self, type, create=True):
def getBaseFolder(self, type, create=True, allow_fallback=True, log_error=False, check_writable=True, deep_check_writable=False):
if type not in default_settings["folder"].keys() + ["base"]:
return None
@@ -1445,17 +1503,33 @@ class Settings(object):
return self._basedir
folder = self.get(["folder", type])
default_folder = self._get_default_folder(type)
if folder is None:
folder = self._get_default_folder(type)
folder = default_folder
if not os.path.exists(folder):
if create:
os.makedirs(folder)
try:
_validate_folder(folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, log_error=log_error)
except:
if folder != default_folder and allow_fallback:
if log_error:
self._logger.error("Invalid configured {} folder at {}, attempting to "
"fall back on default folder at {}".format(type,
folder,
default_folder))
_validate_folder(default_folder, create=create, check_writable=check_writable, deep_check_writable=deep_check_writable, log_error=log_error)
folder = default_folder
try:
del self._config["folder"][type]
if not len(self._config["folder"]):
del self._config["folder"]
self._dirty = True
self._dirty_time = time.time()
self.save()
except KeyError:
pass
else:
raise IOError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
raise
return folder
@@ -1621,7 +1695,7 @@ class Settings(object):
else:
self.set(path, False, **kwargs)
def setBaseFolder(self, type, path, force=False):
def setBaseFolder(self, type, path, force=False, validate=True):
if type not in default_settings["folder"].keys():
return None
@@ -1634,6 +1708,9 @@ class Settings(object):
self._dirty = True
self._dirty_time = time.time()
elif (path != currentPath and path != defaultPath) or force:
if validate:
_validate_folder(path, check_writable=True, deep_check_writable=True)
if not "folder" in self._config.keys():
self._config["folder"] = {}
self._config["folder"][type] = path
@@ -1673,3 +1750,48 @@ def _default_basedir(applicationName):
return os.path.join(os.environ["APPDATA"], applicationName)
else:
return os.path.expanduser(os.path.join("~", "." + applicationName.lower()))
def _validate_folder(folder, create=True, check_writable=True, deep_check_writable=False, log_error=False):
logger = logging.getLogger(__name__)
if not os.path.exists(folder):
if os.path.islink(folder):
# broken symlink, see #2644
raise IOError("Folder at {} appears to be a broken symlink".format(folder))
elif create:
# non existing, but we are allowed to create it
try:
os.makedirs(folder)
except:
if log_error:
logger.exception("Could not create {}".format(folder))
raise IOError("Folder for type {} at {} does not exist and creation failed".format(type, folder))
else:
# not extisting, not allowed to create it
raise IOError("No such folder: {}".format(folder))
elif os.path.isfile(folder):
# hardening against misconfiguration, see #1953
raise IOError("Expected a folder at {} but found a file instead".format(folder))
elif check_writable:
# make sure we can also write into the folder
error = "Folder at {} doesn't appear to be writable, please fix its permissions".format(folder)
if not os.access(folder, os.W_OK):
raise IOError(error)
elif deep_check_writable:
# try to write a file to the folder - on network shares that might be the only reliable way
# to determine whether things are *actually* writable
testfile = os.path.join(folder, ".testballoon.txt")
try:
with open(testfile, "wb") as f:
f.write("test")
os.remove(testfile)
except:
if log_error:
logger.exception("Could not write test file to {}".format(folder))
raise IOError(error)
+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
+59 -11
View File
@@ -31,18 +31,21 @@ GCODE.renderer = (function(){
colorMove: "#00ff00",
colorRetract: "#ff0000",
colorRestart: "#0000ff",
colorHead: "#00ff00",
showMoves: true,
showRetracts: true,
extrusionWidth: 1 * pixelRatio,
// #000000", "#45c7ba", "#a9533a", "#ff44cc", "#dd1177", "#eeee22", "#ffbb55", "#ff5511", "#777788"
sizeRetractSpot: 2 * pixelRatio,
sizeHeadSpot: 2 * pixelRatio,
modelCenter: {x: 0, y: 0},
differentiateColors: true,
showNextLayer: false,
showPreviousLayer: false,
showBoundingBox: false,
showFullSize: false,
showHead: false,
moveModel: true,
zoomInOnModel: false,
@@ -420,6 +423,47 @@ GCODE.renderer = (function(){
ctx.setLineDash([1, 0]);
};
var drawTriangle = function(centerX, centerY, length, up) {
/*
* (cx,cy)
* * ^
* / \ |
* / \ |
* / \ |
* / (x,y) \ | h
* / \ |
* / \ |
* / \ |
* *---------------* v
* (ax,ay) (bx,by)
*/
var ax, bx, cx, ay, by, cy;
var h = Math.sqrt(0.75 * length * length);
ax = centerX - length / 2;
bx = centerX + length / 2;
cx = centerX;
if (up) {
ay = centerY + h / 2;
by = centerY + h / 2;
cy = centerY - h / 2;
} else {
ay = centerY - h / 2;
by = centerY - h / 2;
cy = centerY + h / 2;
}
ctx.beginPath();
ctx.moveTo(ax, ay);
ctx.lineTo(bx, by);
ctx.lineTo(cx, cy);
ctx.lineTo(ax, ay);
ctx.stroke();
ctx.fill();
};
var drawLayer = function(layerNum, fromProgress, toProgress, isNotCurrentLayer){
log.trace("Drawing layer " + layerNum + " from " + fromProgress + " to " + toProgress + " (current: " + !isNotCurrentLayer + ")");
@@ -505,15 +549,12 @@ GCODE.renderer = (function(){
if (!cmds[i].extrude && !cmds[i].noMove) {
// neither extrusion nor move
if (cmds[i].retract == -1) {
if (cmds[i].retract === -1) {
// retract => draw dot if configured to do so
if (renderOptions["showRetracts"]) {
ctx.strokeStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html();
ctx.fillStyle = pusher.color(renderOptions["colorRetract"]).shade(shade).alpha(alpha).html();
ctx.beginPath();
ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true);
ctx.stroke();
ctx.fill();
drawTriangle(prevX, prevY, renderOptions["sizeRetractSpot"] * 2, true);
}
}
@@ -526,13 +567,13 @@ GCODE.renderer = (function(){
ctx.stroke();
}
} else if(cmds[i].extrude) {
if (cmds[i].retract == 0) {
if (cmds[i].retract === 0) {
// no retraction => real extrusion move, use tool color to draw line
ctx.strokeStyle = pusher.color(renderOptions["colorLine"][tool]).shade(shade).alpha(alpha).html();
ctx.lineWidth = renderOptions['extrusionWidth'];
ctx.beginPath();
ctx.moveTo(prevX, prevY);
if (cmds[i].direction !== undefined && cmds[i].direction != 0){
if (cmds[i].direction !== undefined && cmds[i].direction !== 0){
var cmd = cmds[i];
var di = cmd.i*zoomFactor;
var dj = -1*cmd.j*zoomFactor; // Y-coordinate is inverted
@@ -551,10 +592,7 @@ GCODE.renderer = (function(){
if (renderOptions["showRetracts"]) {
ctx.strokeStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html();
ctx.fillStyle = pusher.color(renderOptions["colorRestart"]).shade(shade).alpha(alpha).html();
ctx.beginPath();
ctx.arc(prevX, prevY, renderOptions["sizeRetractSpot"], 0, Math.PI*2, true);
ctx.stroke();
ctx.fill();
drawTriangle(prevX, prevY, renderOptions["sizeRetractSpot"] * 2, false);
}
}
}
@@ -563,7 +601,17 @@ GCODE.renderer = (function(){
prevX = x * zoomFactor;
prevY = y * zoomFactor;
}
ctx.stroke();
if (renderOptions["showHead"]) {
ctx.strokeStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html();
ctx.fillStyle = pusher.color(renderOptions["colorHead"]).shade(shade).alpha(alpha).html();
ctx.beginPath();
ctx.arc(prevX, prevY, renderOptions["sizeHeadSpot"], 0, Math.PI*2, true);
ctx.stroke();
ctx.fill();
}
};
var applyOffsets = function() {
+27 -4
View File
@@ -218,6 +218,9 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
};
self._printerErrorCancelNotification = undefined;
self._printerErrorDisconnectNotification = undefined;
self._printerResetNotification = undefined;
self._onEvent = function(event) {
self._ifInitialized(function() {
var type = event.data["type"];
@@ -226,7 +229,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
log.debug("Got event " + type + " with payload: " + JSON.stringify(payload));
if (type === "PrintCancelling" && payload.firmwareError) {
new PNotify({
if (self._printerErrorCancelNotification !== undefined) {
self._printerErrorCancelNotification.remove();
}
self._printerErrorCancelNotification = new PNotify({
title: gettext("Error reported by printer"),
text: _.sprintf(gettext("Your printer's firmware reported an error. Due to that the ongoing print job will be cancelled. Reported error: %(firmwareError)s"), payload),
type: "error",
@@ -271,7 +277,10 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
}
if (title && text) {
new PNotify({
if (self._printerErrorDisconnectNotification !== undefined) {
self._printerErrorDisconnectNotification.remove();
}
self._printerErrorDisconnectNotification = new PNotify({
title: title,
text: text,
type: "error",
@@ -279,9 +288,23 @@ function DataUpdater(allViewModels, connectCallback, disconnectCallback) {
});
}
} else if (type === "PrinterReset") {
new PNotify({
var severity = undefined,
text = undefined;
if (payload.idle) {
text = gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");
severity = "alert";
} else {
text = gettext("It looks like your printer reset while a connection was active. Due to this the ongoing job was aborted. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD.");
severity = "error";
}
if (self._printerResetNotification !== undefined) {
self._printerResetNotification.remove();
}
self._printerResetNotification = new PNotify({
title: gettext("Printer reset detected"),
text: gettext("It looks like your printer reset while a connection was active. If this was intentional you may safely ignore this message. Otherwise you should investigate why your printer reset itself, since this will interrupt prints and also file transfers to your printer's SD."),
text: text,
type: severity,
hide: false
});
}
+184 -25
View File
@@ -1,4 +1,4 @@
function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSorting, defaultFilters, exclusiveFilters, filesPerPage) {
function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSorting, defaultFilters, exclusiveFilters, defaultPageSize) {
var self = this;
self.listType = listType;
@@ -7,6 +7,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
self.defaultSorting = defaultSorting;
self.defaultFilters = defaultFilters;
self.exclusiveFilters = exclusiveFilters;
self.defaultPageSize = defaultPageSize;
self.searchFunction = undefined;
@@ -14,12 +15,18 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
self.allSize = ko.observable(0);
self.items = ko.observableArray([]);
self.pageSize = ko.observable(filesPerPage);
self.pageSize = ko.observable(self.defaultPageSize);
self.currentPage = ko.observable(0);
self.currentSorting = ko.observable(self.defaultSorting);
self.currentFilters = ko.observableArray(self.defaultFilters);
self.selectedItem = ko.observable(undefined);
self.storageIds = {
"currentSorting": self.listType + "." + "currentSorting",
"currentFilters": self.listType + "." + "currentFilters",
"pageSize": self.listType + "." + "pageSize",
};
//~~ item handling
self.refresh = function() {
@@ -27,6 +34,7 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
};
self.updateItems = function(items) {
if (items === undefined) items = [];
self.allItems = items;
self.allSize(items.length);
self._updateItems();
@@ -55,18 +63,26 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
};
self.removeItem = function(matcher) {
var item = self.getItem(matcher, true);
if (item === undefined) {
return;
}
var index = self.allItems.indexOf(item);
var index = self.getIndex(matcher, true);
if (index > -1) {
self.allItems.splice(index, 1);
self._updateItems();
}
};
self.updateItem = function(matcher, item) {
var index = self.allItems.findIndex(matcher);
if (index > -1) {
self.allItems[index] = item;
self._updateItems();
}
};
self.addItem = function(item) {
self.allItems.push(item);
self._updateItems();
}
//~~ pagination
self.paginatedItems = ko.dependentObservable(function() {
@@ -146,20 +162,29 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
}
};
self.getItem = function(matcher, all) {
self.getIndex = function(matcher, all) {
var itemList;
if (all !== undefined && all === true) {
itemList = self.allItems;
} else {
itemList = self.items();
}
for (var i = 0; i < itemList.length; i++) {
if (matcher(itemList[i])) {
return itemList[i];
return i;
}
}
return -1;
}
return undefined;
self.getItem = function(matcher, all) {
var index = self.getIndex(matcher, all);
if (all !== undefined && all === true) {
return index > -1 ? self.allItems[index] : undefined;
} else {
return index > -1 ? self.items()[index] : undefined;
}
};
self.resetPage = function() {
@@ -281,16 +306,16 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
if ( self._initializeLocalStorage() ) {
var currentSorting = self.currentSorting();
if (currentSorting !== undefined)
localStorage[self.listType + "." + "currentSorting"] = currentSorting;
localStorage[self.storageIds.currentSorting] = currentSorting;
else
localStorage[self.listType + "." + "currentSorting"] = undefined;
localStorage[self.storageIds.currentSorting] = undefined;
}
};
self._loadCurrentSortingFromLocalStorage = function() {
if ( self._initializeLocalStorage() ) {
if (_.contains(_.keys(supportedSorting), localStorage[self.listType + "." + "currentSorting"]))
self.currentSorting(localStorage[self.listType + "." + "currentSorting"]);
if (_.contains(_.keys(supportedSorting), localStorage[self.storageIds.currentSorting]))
self.currentSorting(localStorage[self.storageIds.currentSorting]);
else
self.currentSorting(defaultSorting);
}
@@ -299,31 +324,47 @@ function ItemListHelper(listType, supportedSorting, supportedFilters, defaultSor
self._saveCurrentFiltersToLocalStorage = function() {
if ( self._initializeLocalStorage() ) {
var filters = _.intersection(_.keys(self.supportedFilters), self.currentFilters());
localStorage[self.listType + "." + "currentFilters"] = JSON.stringify(filters);
localStorage[self.storageIds.currentFilters] = JSON.stringify(filters);
}
};
self._loadCurrentFiltersFromLocalStorage = function() {
if ( self._initializeLocalStorage() ) {
self.currentFilters(_.intersection(_.keys(self.supportedFilters), JSON.parse(localStorage[self.listType + "." + "currentFilters"])));
self.currentFilters(_.intersection(_.keys(self.supportedFilters), JSON.parse(localStorage[self.storageIds.currentFilters])));
}
};
self._savePageSizeToLocalStorage = function(pageSize) {
if (self._initializeLocalStorage()) {
localStorage[self.storageIds.pageSize] = pageSize;
}
}
self.pageSize.subscribe(self._savePageSizeToLocalStorage);
self._loadPageSizeFromLocalStorage = function() {
if (self._initializeLocalStorage) {
self.pageSize(parseInt(localStorage[self.storageIds.pageSize]));
}
}
self._initializeLocalStorage = function() {
if (!Modernizr.localstorage)
return false;
if (localStorage[self.listType + "." + "currentSorting"] !== undefined && localStorage[self.listType + "." + "currentFilters"] !== undefined && JSON.parse(localStorage[self.listType + "." + "currentFilters"]) instanceof Array)
if (localStorage[self.storageIds.currentSorting] !== undefined && localStorage[self.storageIds.currentFilters] !== undefined && JSON.parse(localStorage[self.storageIds.currentFilters]) instanceof Array && localStorage[self.storageIds.pageSize] !== undefined)
return true;
localStorage[self.listType + "." + "currentSorting"] = self.defaultSorting;
localStorage[self.listType + "." + "currentFilters"] = JSON.stringify(self.defaultFilters);
localStorage[self.storageIds.currentSorting] = self.defaultSorting;
localStorage[self.storageIds.currentFilters] = JSON.stringify(self.defaultFilters);
localStorage[self.storageIds.pageSize] = self.defaultPageSize;
return true;
};
self._loadCurrentFiltersFromLocalStorage();
self._loadCurrentSortingFromLocalStorage();
self._loadPageSizeFromLocalStorage();
}
function formatSize(bytes) {
@@ -609,6 +650,7 @@ function showMessageDialog(msg, options) {
var onclose = options.onclose || undefined;
var onshow = options.onshow || undefined;
var onshown = options.onshown || undefined;
var nofade = options.nofade || false;
if (_.isString(message)) {
message = $("<p>" + message + "</p>");
@@ -619,7 +661,11 @@ function showMessageDialog(msg, options) {
var modalFooter = $('<a href="javascript:void(0)" class="btn" data-dismiss="modal" aria-hidden="true">' + close + '</a>');
var modal = $('<div></div>')
.addClass('modal hide fade')
.addClass("modal hide");
if (!nofade) {
modal.addClass("fade");
}
modal
.append($('<div></div>').addClass('modal-header').append(modalHeader))
.append($('<div></div>').addClass('modal-body').append(modalBody))
.append($('<div></div>').addClass('modal-footer').append(modalFooter));
@@ -652,17 +698,27 @@ function showConfirmationDialog(msg, onacknowledge, options) {
}
var title = options.title || gettext("Are you sure?");
var message = options.message || "";
var question = options.question || gettext("Are you sure you want to proceed?");
var html = options.html;
var cancel = options.cancel || gettext("Cancel");
var proceed = options.proceed || gettext("Proceed");
var proceedClass = options.proceedClass || "danger";
var onproceed = options.onproceed || undefined;
var onclose = options.onclose || undefined;
var dialogClass = options.dialogClass || "";
var nofade = options.nofade || false;
var modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>' + title + '</h3>');
var modalBody = $('<p>' + message + '</p><p>' + question + '</p>');
var modalBody;
if (html) {
modalBody = $(html);
} else {
modalBody = $('<p>' + message + '</p><p>' + question + '</p>');
}
var cancelButton = $('<a href="javascript:void(0)" class="btn">' + cancel + '</a>')
.attr("data-dismiss", "modal")
@@ -671,8 +727,11 @@ function showConfirmationDialog(msg, onacknowledge, options) {
.addClass("btn-" + proceedClass);
var modal = $('<div></div>')
.addClass('modal hide fade')
.addClass(dialogClass)
.addClass('modal hide');
if (!nofade) {
modal.addClass('fade');
}
modal.addClass(dialogClass)
.append($('<div></div>').addClass('modal-header').append(modalHeader))
.append($('<div></div>').addClass('modal-body').append(modalBody))
.append($('<div></div>').addClass('modal-footer').append(cancelButton).append(proceedButton));
@@ -694,6 +753,106 @@ function showConfirmationDialog(msg, onacknowledge, options) {
return modal;
}
function showSelectionDialog(options) {
var title = options.title;
var message = options.message || undefined;
var selections = options.selections || [];
var maycancel = options.maycancel || false;
var cancel = options.cancel || undefined;
var onselect = options.onselect || undefined;
var onclose = options.onclose || undefined;
var dialogClass = options.dialogClass || "";
var nofade = options.nofade || false;
// header
var modalHeader;
if (maycancel) {
modalHeader = $('<a href="javascript:void(0)" class="close" data-dismiss="modal" aria-hidden="true">&times;</a><h3>' + title + '</h3>');
} else {
modalHeader = $('<h3>' + title + '</h3>');
}
// body
var buttons = [];
var selectionBody = $("<div></div>");
var container;
var additionalClass;
if (selections.length === 1) {
container = selectionBody;
additionalClass = "btn-block";
} else if (selections.length === 2) {
container = $("<div class='row-fluid'></div>");
selectionBody.append(container);
additionalClass = "span6"
} else {
container = $("<div class='row-fluid'></div>");
selectionBody.append(container);
additionalClass = "span6 offset3";
}
_.each(selections, function(s, i) {
var button = $('<button class="btn" data-index="' + i + '">' + selections[i] + '</button>');
if (additionalClass) {
button.addClass(additionalClass);
}
container.append(button);
buttons.push(button);
if (selections.length > 2 && i < selections.length - 1) {
container = $("<div class='row-fluid'></div>");
selectionBody.append(container);
}
});
// divs
var headerDiv = $('<div></div>').addClass('modal-header').append(modalHeader);
var bodyDiv = $('<div></div>').addClass('modal-body');
if (message) {
bodyDiv.append($('<p>' + message + '</p>'));
}
bodyDiv.append(selectionBody);
// create modal and do final wiring up
var modal = $('<div></div>')
.addClass('modal hide');
if (!nofade) {
modal.addClass('fade');
}
if (!cancel) {
modal.data("backdrop", "static").data("keyboard", "false");
}
modal.addClass(dialogClass)
.append(headerDiv)
.append(bodyDiv);
modal.on('hidden', function(event) {
if (onclose && _.isFunction(onclose)) {
onclose(event);
}
});
modal.modal("show");
_.each(buttons, function(button) {
button.click(function(e) {
e.preventDefault();
var index = button.data("index");
if (index < 0) {
return;
}
if (onselect && _.isFunction(onselect)) {
onselect(index, e);
}
modal.modal("hide");
})
});
return modal;
}
/**
* Shows a progress modal depending on a supplied promise.
*
@@ -1053,7 +1212,7 @@ function callViewModelIf(viewModel, method, condition, callback, raiseErrors) {
condition = function() { return true; };
}
if (!viewModel.hasOwnProperty(method) || !_.isFunction(viewModel[method]) || !condition(viewModel, method)) return;
if (!_.isFunction(viewModel[method]) || !condition(viewModel, method)) return;
var parameters = undefined;
if (!_.isFunction(callback)) {
+3 -1
View File
@@ -49,7 +49,8 @@ $(function() {
mobile: false,
desktop: false
}
},
viewmodels: {}
};
var browserVisibilityCallbacks = [];
@@ -400,6 +401,7 @@ $(function() {
pass++;
}
log.info("... dependency resolution done");
OctoPrint.coreui.viewmodels = viewModelMap;
//~~ some additional hooks and initializations
@@ -151,6 +151,10 @@ $(function() {
}
};
self.onEventSettingsUpdated = function() {
self.requestData();
}
self.onStartup = function() {
var connectionTab = $("#connection");
connectionTab.on("show", function() {
@@ -8,6 +8,7 @@ $(function() {
self.slicing = parameters[3];
self.printerProfiles=parameters[4];
self.filesListVisible = ko.observable(true);
self.isErrorOrClosed = ko.observable(undefined);
self.isOperational = ko.observable(undefined);
self.isPrinting = ko.observable(undefined);
@@ -98,13 +99,13 @@ $(function() {
"upload": function(a, b) {
// sorts descending
if (b["date"] === undefined || a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
if (a["date"] === undefined || a["date"] < b["date"]) return 1;
return 0;
},
"size": function(a, b) {
// sorts descending
if (b["size"] === undefined || a["size"] > b["size"]) return -1;
if (a["size"] < b["size"]) return 1;
if (a["size"] === undefined || a["size"] < b["size"]) return 1;
return 0;
}
},
@@ -276,6 +277,20 @@ $(function() {
self.allItems(files);
// Sanity check file list - see #2572
var nonrecursive = false;
_.each(files, function(file) {
if (file.type === "folder" && file.children === undefined) {
nonrecursive = true;
}
});
if (nonrecursive) {
log.error("At least one folder doesn't have a 'children' element defined. That means the file list request " +
"wasn't actually made with 'recursive=true' in the query.\n\n" +
"This can happen on wrong reverse proxy configs that " +
"swallow up query parameters, see https://github.com/foosel/OctoPrint/issues/2572");
}
if (!switchToPath) {
var currentPath = self.currentPath();
if (currentPath === undefined) {
@@ -294,10 +309,7 @@ $(function() {
var entryElement = self.getEntryElement({path: focus.path, origin: focus.location});
if (entryElement) {
// scroll to uploaded element
var entryOffset = entryElement.offsetTop;
self.listElement.slimScroll({
scrollTo: entryOffset + "px"
});
self.listElement.scrollTop(entryElement.offsetTop);
// highlight uploaded element
var element = $(entryElement);
@@ -321,6 +333,11 @@ $(function() {
};
self.changeFolder = function(data) {
if (data.children === undefined) {
log.error("Can't switch to folder '" + data.path + "', no children available");
return;
}
self.currentPath(data.path);
self.listHelper.updateItems(data.children);
self.highlightCurrentFilename();
@@ -786,14 +803,16 @@ $(function() {
var files = $("#files");
if (files.hasClass("in")) {
files.removeClass("overflow_visible");
self.filesListVisible(false);
} else {
setTimeout(function() {
files.addClass("overflow_visible");
self.filesListVisible(true);
}, 100);
}
});
self.listElement = $(".gcode_files");
self.listElement = $("#files").find(".scroll-wrapper");
self.addFolderDialog = $("#add_folder_dialog");
self.addFolderDialog.on("shown", function() {
@@ -46,6 +46,7 @@ $(function() {
self.renderer_zoomOnModel = ko.observable(false);
self.renderer_showMoves = ko.observable(true);
self.renderer_showRetracts = ko.observable(true);
self.renderer_showPrinthead = ko.observable(true);
self.renderer_showBoundingBox = ko.observable(false);
self.renderer_showFullSize = ko.observable(false);
self.renderer_extrusionWidthEnabled = ko.observable(false);
@@ -73,6 +74,7 @@ $(function() {
centerViewport: self.renderer_centerViewport(),
showMoves: self.renderer_showMoves(),
showRetracts: self.renderer_showRetracts(),
showHead: self.renderer_showPrinthead(),
showBoundingBox: self.renderer_showBoundingBox(),
showFullSize: self.renderer_showFullSize(),
extrusionWidth: self.renderer_extrusionWidthEnabled() ? self.renderer_extrusionWidth() : 1,
@@ -116,6 +118,7 @@ $(function() {
self.renderer_zoomOnModel.subscribe(self.rendererOptionUpdated);
self.renderer_showMoves.subscribe(self.rendererOptionUpdated);
self.renderer_showRetracts.subscribe(self.rendererOptionUpdated);
self.renderer_showPrinthead.subscribe(self.rendererOptionUpdated);
self.renderer_showBoundingBox.subscribe(self.rendererOptionUpdated);
self.renderer_showFullSize.subscribe(self.rendererOptionUpdated);
self.renderer_extrusionWidthEnabled.subscribe(self.rendererOptionUpdated);
@@ -332,6 +335,7 @@ $(function() {
self.renderer_zoomOnModel(false);
self.renderer_showMoves(true);
self.renderer_showRetracts(true);
self.renderer_showPrinthead(true);
self.renderer_showBoundingBox(false);
self.renderer_showFullSize(false);
self.renderer_extrusionWidthEnabled(false);
@@ -702,6 +706,7 @@ $(function() {
current["zoomOnModel"] = self.renderer_zoomOnModel();
current["showMoves"] = self.renderer_showMoves();
current["showRetracts"] = self.renderer_showRetracts();
current["showPrinthead"] = self.renderer_showPrinthead();
current["showPrevious"] = self.renderer_showPrevious();
current["showNext"] = self.renderer_showNext();
current["showFullsize"] = self.renderer_showFullSize();
@@ -733,6 +738,7 @@ $(function() {
if (current["zoomOnModel"] !== undefined) self.renderer_zoomOnModel(current["zoomOnModel"]) ;
if (current["showMoves"] !== undefined) self.renderer_showMoves(current["showMoves"]) ;
if (current["showRetracts"] !== undefined) self.renderer_showRetracts(current["showRetracts"]) ;
if (current["showPrinthead"] !== undefined) self.renderer_showPrinthead(current["showPrinthead"]);
if (current["showPrevious"] !== undefined) self.renderer_showPrevious(current["showPrevious"]) ;
if (current["showNext"] !== undefined) self.renderer_showNext(current["showNext"]) ;
if (current["showFullsize"] !== undefined) self.renderer_showFullSize(current["showFullsize"]) ;
@@ -18,7 +18,7 @@ $(function() {
self.isSdReady = ko.observable(undefined);
self.enablePrint = ko.pureComputed(function() {
return self.isOperational() && self.isReady() && !self.isPrinting() && !self.isCancelling() && !self.isPausing() && self.loginState.isUser() && self.filename() != undefined;
return self.isOperational() && self.isReady() && !self.isPrinting() && !self.isCancelling() && !self.isPausing() && self.loginState.isUser() && self.filename();
});
self.enablePause = ko.pureComputed(function() {
return self.isOperational() && (self.isPrinting() || self.isPaused()) && !self.isCancelling() && !self.isPausing() && self.loginState.isUser();
@@ -38,6 +38,7 @@ $(function() {
self.printTimeLeftOrigin = ko.observable(undefined);
self.sd = ko.observable(undefined);
self.timelapse = ko.observable(undefined);
self.user = ko.observable(undefined);
self.busyFiles = ko.observableArray([]);
@@ -167,6 +168,20 @@ $(function() {
}
});
self.userString = ko.pureComputed(function() {
var user = self.user();
if (!CONFIG_ACCESS_CONTROL || user === "_dummy") {
return "";
}
if (user === "_api") {
user = "API client";
}
var file = self.filename();
return (user ? user : (file ? "-" : ""));
});
self.fromCurrentData = function(data) {
self._fromData(data);
};
@@ -244,6 +259,8 @@ $(function() {
});
}
self.filament(result);
self.user(data.user);
};
self._processProgressData = function(data) {
@@ -307,7 +324,8 @@ $(function() {
proceed: gettext("Yes"),
onproceed: function() {
OctoPrint.job.cancel();
}
},
nofade: true
});
}
};
@@ -143,7 +143,6 @@ $(function() {
self.feature_printCancelConfirmation = ko.observable(undefined);
self.feature_g90InfluencesExtruder = ko.observable(undefined);
self.feature_autoUppercaseBlacklist = ko.observable(undefined);
self.feature_legacyPluginAssets = ko.observable(undefined);
self.serial_port = ko.observable();
self.serial_baudrate = ko.observable();
@@ -159,6 +158,8 @@ $(function() {
self.serial_timeoutTemperatureAutoreport = ko.observable(undefined);
self.serial_timeoutSdStatus = ko.observable(undefined);
self.serial_timeoutSdStatusAutoreport = ko.observable(undefined);
self.serial_timeoutBaudrateDetectionPause = ko.observable(undefined);
self.serial_timeoutPositionLogWait = ko.observable(undefined);
self.serial_log = ko.observable(undefined);
self.serial_additionalPorts = ko.observable(undefined);
self.serial_additionalBaudrates = ko.observable(undefined);
@@ -167,6 +168,7 @@ $(function() {
self.serial_helloCommand = ko.observable(undefined);
self.serial_serialErrorBehaviour = ko.observable("cancel");
self.serial_triggerOkForM29 = ko.observable(undefined);
self.serial_blockM0M1 = ko.observable(undefined);
self.serial_waitForStart = ko.observable(undefined);
self.serial_sendChecksum = ko.observable("print");
self.serial_sdRelativePath = ko.observable(undefined);
@@ -251,6 +253,23 @@ $(function() {
self.server_onlineCheckBroken(false);
};
var folderTypes = ["uploads", "timelapse", "timelapseTmp", "logs", "watched"];
self.testFolderConfigText = {};
self.testFolderConfigOk = {};
self.testFolderConfigBroken = {};
_.each(folderTypes, function(folderType) {
self.testFolderConfigText[folderType] = ko.observable("");
self.testFolderConfigOk[folderType] = ko.observable(false);
self.testFolderConfigBroken[folderType] = ko.observable(false);
});
self.testFolderConfigReset = function() {
_.each(folderTypes, function(folderType) {
self.testFolderConfigText[folderType]("");
self.testFolderConfigOk[folderType](false);
self.testFolderConfigBroken[folderType](false);
});
};
self.observableCopies = {
"feature_waitForStart": "serial_waitForStart",
"feature_sendChecksum": "serial_sendChecksum",
@@ -330,23 +349,36 @@ $(function() {
method: "GET",
response: "bytes",
timeout: self.webcam_snapshotTimeout(),
validSsl: self.webcam_snapshotSslValidation()
validSsl: self.webcam_snapshotSslValidation(),
content_type_whitelist: ["image/*"]
})
.done(function(response) {
if (!response.result) {
if (response.status && response.response && response.response.content_type) {
// we could contact the server, but something else was wrong, probably the mime type
errorText = gettext("Could retrieve the snapshot URL, but it didn't look like an " +
"image. Got this as a content type header: <code>%(content_type)s</code>. Please " +
"double check that the URL is returning static images, not multipart data " +
"or videos.");
errorText = _.sprintf(errorText, {content_type: response.response.content_type});
}
showMessageDialog({
title: errorTitle,
message: errorText
message: errorText,
onclose: function() {
self.testWebcamSnapshotUrlBusy(false);
}
});
return;
}
var content = response.response.content;
var mimeType = "image/jpeg";
var contentType = response.response.content_type
var headers = response.response.headers;
if (headers && headers["content-type"]) {
mimeType = headers["content-type"].split(";")[0];
var mimeType = "image/jpeg";
if (contentType) {
mimeType = contentType.split(";")[0];
}
var text = gettext("If you see your webcam snapshot picture below, the entered snapshot URL is ok.");
@@ -423,9 +455,48 @@ $(function() {
});
};
self.testFolderConfigBusy = ko.observable(false);
self.testFolderConfig = function(folder) {
var observable = "folder_" + folder;
if (!self.hasOwnProperty(observable)) return;
if (self.testFolderConfigBusy()) return;
self.testFolderConfigBusy(true);
var opts = {
check_type: "dir",
check_access: "w",
allow_create_dir: true,
check_writable_dir: true
};
var path = self[observable]();
OctoPrint.util.testPath(path, opts)
.done(function(response) {
if (!response.result) {
if (response.broken_symlink) {
self.testFolderConfigText[folder](gettext("The path is a broken symlink."));
} else if (!response.exists) {
self.testFolderConfigText[folder](gettext("The path does not exist and cannot be created."));
} else if (!response.typeok) {
self.testFolderConfigText[folder](gettext("The path is not a folder."));
} else if (!response.access) {
self.testFolderConfigText[folder](gettext("The path is not writable."));
}
} else {
self.testFolderConfigText[folder](gettext("The path is valid"));
}
self.testFolderConfigOk[folder](response.result);
self.testFolderConfigBroken[folder](!response.result);
})
.always(function() {
self.testFolderConfigBusy(false);
});
};
self.onSettingsHidden = function() {
self.webcam_ffmpegPathReset();
self.server_onlineCheckReset();
self.testFolderConfigReset();
};
self.isDialogActive = function() {
@@ -729,6 +800,23 @@ $(function() {
});
return result;
}
},
temperature: {
profiles: function() {
var result = [];
_.each(self.temperature_profiles(), function(profile) {
try {
result.push({
name: profile.name,
extruder: Math.floor(_.isNumber(profile.extruder) ? profile.extruder : parseInt(profile.extruder)),
bed: Math.floor(_.isNumber(profile.bed) ? profile.bed : parseInt(profile.bed))
});
} catch (ex) {
// ignore
}
});
return result;
}
}
};
@@ -869,6 +957,13 @@ $(function() {
firstRequest.resolve();
};
self.cancelData = function () {
// revert unsaved changes
self.fromResponse(self.lastReceivedSettings);
self.hide();
}
self.saveData = function (data, successCallback, setAsSending) {
var options;
if (_.isPlainObject(successCallback)) {
@@ -54,11 +54,12 @@ $(function() {
});
self.editorPasswordMismatch = ko.pureComputed(function() {
return self.editorPassword() != self.editorRepeatedPassword();
return self.editorPassword() !== self.editorRepeatedPassword();
});
self.requestData = function() {
if (!CONFIG_ACCESS_CONTROL) return;
if (!self.loginState.isAdmin()) return;
OctoPrint.users.list()
.done(self.fromResponse);
@@ -97,8 +98,20 @@ $(function() {
self.showEditUserDialog = function(user) {
if (!CONFIG_ACCESS_CONTROL) return;
self.currentUser(user);
self.editUserDialog.modal("show");
var process = function(user) {
self.currentUser(user);
self.editUserDialog.modal("show");
};
// make sure we have the current user data, see #2534
OctoPrint.users.get(user.name)
.done(function(data) {
process(data);
})
.fail(function() {
log.warn("Could not fetch current user data, proceeding with client side data copy");
process(user);
});
};
self.confirmEditUser = function() {
@@ -175,6 +188,7 @@ $(function() {
if (!user) {
throw OctoPrint.InvalidArgumentError("user must be set");
}
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
return OctoPrint.users.add(user)
.done(self.fromResponse);
@@ -184,8 +198,9 @@ $(function() {
if (!user) {
throw OctoPrint.InvalidArgumentError("user must be set");
}
if (!self.loginState.isAdmin()) return $.Deferred().reject("You are not authorized to perform this action").promise();
if (user.name == self.loginState.username()) {
if (user.name === self.loginState.username()) {
// we do not allow to delete ourselves
new PNotify({
title: gettext("Not possible"),
@@ -213,7 +228,10 @@ $(function() {
};
self.generateApikey = function(username) {
return OctoPrint.users.generateApiKey(username);
return OctoPrint.users.generateApiKey(username)
.done(function() {
self.requestData();
});
};
self.deleteApikey = function(username) {
@@ -221,9 +239,7 @@ $(function() {
};
self.onUserLoggedIn = function(user) {
if (user.admin) {
self.requestData();
}
self.requestData();
}
}
@@ -25,7 +25,7 @@ $(function() {
self.access_apikey(undefined);
self.interface_language("_default");
if (newUser != undefined) {
if (newUser !== undefined) {
self.access_apikey(newUser.apikey);
if (newUser.settings.hasOwnProperty("interface") && newUser.settings.interface.hasOwnProperty("language")) {
self.interface_language(newUser.settings.interface.language);
@@ -34,18 +34,30 @@ $(function() {
});
self.passwordMismatch = ko.pureComputed(function() {
return self.access_password() != self.access_repeatedPassword();
return self.access_password() !== self.access_repeatedPassword();
});
self.show = function(user) {
if (!CONFIG_ACCESS_CONTROL) return;
if (user == undefined) {
if (user === undefined) {
user = self.loginState.currentUser();
}
self.currentUser(user);
self.userSettingsDialog.modal("show");
var process = function(user) {
self.currentUser(user);
self.userSettingsDialog.modal("show");
};
// make sure we have the current user data, see #2534
OctoPrint.users.get(user.name)
.done(function(data) {
process(data);
})
.fail(function() {
log.warn("Could not fetch current user data, proceeding with client side data copy");
process(user);
});
};
self.save = function() {
File diff suppressed because it is too large. Load diff
+2 -4
View File
@@ -1,4 +1,2 @@
/*! jQuery v2.2.4 | (c) jQuery Foundation | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="2.2.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(n.isPlainObject(d)||(e=n.isArray(d)))?(e?(e=!1,f=c&&n.isArray(c)?c:[]):f=c&&n.isPlainObject(c)?c:{},g[b]=n.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isPlainObject:function(a){var b;if("object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype||{},"isPrototypeOf"))return!1;for(b in a);return void 0===b||k.call(a,b)},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(a){var b,c=eval;a=n.trim(a),a&&(1===a.indexOf("use strict")?(b=d.createElement("script"),b.text=a,d.head.appendChild(b).parentNode.removeChild(b)):c(a))},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:h.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;c>d;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(c=a[b],b=a,a=c),n.isFunction(a)?(d=e.call(arguments,2),f=function(){return a.apply(b||this,d.concat(e.call(arguments)))},f.guid=a.guid=a.guid||n.guid++,f):void 0},now:Date.now,support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new ReLine truncated
}catch(e){}O.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return O.hasData(a)||N.hasData(a)},data:function(a,b,c){return O.access(a,b,c)},removeData:function(a,b){O.remove(a,b)},_data:function(a,b,c){return N.access(a,b,c)},_removeData:function(a,b){N.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=O.get(f),1===f.nodeType&&!N.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),R(f,d,e[d])));N.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){O.set(this,a)}):K(this,function(b){var c,d;if(f&&void 0===b){if(c=O.get(f,a)||O.get(f,a.replace(Q,"-$&").toLowerCase()),void 0!==c)return c;if(d=n.camelCase(a),c=O.get(f,d),void 0!==c)return c;if(c=R(f,d,void 0),void 0!==c)return c}else d=n.camelCase(a),this.each(function(){var c=O.get(this,d);O.set(this,d,b),a.indexOf("-")>-1&&void 0!==c&&O.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){O.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=N.get(a,b),c&&(!d||n.isArray(c)?d=N.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return N.get(a,c)||N.access(a,c,{empty:n.Callbacks("once memory").add(function(){N.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=N.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var S=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=new RegExp("^(?:([+-])=|)("+S+")([a-z%]*)$","i"),U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function W(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&T.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var X=/^(?:checkbox|radio)$/i,Y=/<([\w:-]+)/,Z=/^$|\/(?:java|ecma)script/i,$={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};$.optgroup=$.option,$.tbody=$.tfoot=$.colgroup=$.caption=$.thead,$.th=$.td;function _(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function aa(a,b){for(var c=0,d=a.length;d>c;c++)N.set(a[c],"globalEval",!b||N.get(b[c],"globalEval"))}var ba=/<|&#?\w+;/;function ca(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],o=0,p=a.length;p>o;o++)if(f=a[o],f||0===f)if("object"===n.type(f))n.merge(m,f.nodeType?[f]:f);else if(ba.test(f)){g=g||l.appendChild(b.createElement("div")),h=(Y.exec(f)||["",""])[1].toLowerCase(),i=$[h]||$._default,g.innerHTML=i[1]+n.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;n.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",o=0;while(f=m[o++])if(d&&n.inArray(f,d)>-1)e&&e.push(f);else if(j=n.contains(f.ownerDocument,f),g=_(l.appendChild(f),"script"),j&&aa(g),c){k=0;while(f=g[k++])Z.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var da=/^key/,ea=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,fa=/^([^.]*)(?:\.(.+)|)/;function ga(){return!0}function ha(){return!1}function ia(){try{return d.activeElement}catch(a){}}function ja(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);forLine truncated
void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):cb.test(a.nodeName)||db.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this});var eb=/[\t\r\n\f]/g;function fb(a){return a.getAttribute&&a.getAttribute("class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,fb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,fb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=fb(c),d=1===c.nodeType&&(" "+e+" ").replace(eb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,fb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=fb(this),b&&N.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":N.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+fb(c)+" ").replace(eb," ").indexOf(b)>-1)return!0;return!1}});var gb=/\r/g,hb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(gb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(hb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=n.inArray(n.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var ib=/^(?:focusinfocus|focusoutblur)$/;n.extend(n.event,{trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!ib.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),l=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},f||!o.trigger||o.trigger.apply(e,c)!==!1)){if(!f&&!o.noBubble&&!n.isWindow(e)){for(j=o.delegateType||q,ib.test(j+q)||(h=h.parentNode);h;h=h.parentNode)p.push(h),i=h;i===(e.ownerDocument||d)&&p.push(i.defaultView||i.parentWindow||a)}g=0;while((h=p[g++])&&!b.isPropagationStopped())b.type=g>1?j:o.bindType||q,m=(N.get(h,"events")||{})[b.type]&&N.get(h,"handle"),m&&m.apply(h,c),m=l&&h[l],m&&m.apply&&L(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=q,f||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==Line truncated
/*! jQuery v3.3.1 | (c) JS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){"use strict";var n=[],r=e.document,i=Object.getPrototypeOf,o=n.slice,a=n.concat,s=n.push,u=n.indexOf,l={},c=l.toString,f=l.hasOwnProperty,p=f.toString,d=p.call(Object),h={},g=function e(t){return"function"==typeof t&&"number"!=typeof t.nodeType},y=function e(t){return null!=t&&t===t.window},v={type:!0,src:!0,noModule:!0};function m(e,t,n){var i,o=(t=t||r).createElement("script");if(o.text=e,n)for(i in v)n[i]&&(o[i]=n[i]);t.head.appendChild(o).parentNode.removeChild(o)}function x(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[c.call(e)]||"object":typeof e}var b="3.3.1",w=function(e,t){return new w.fn.init(e,t)},T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;w.fn=w.prototype={jquery:"3.3.1",constructor:w,length:0,toArray:function(){return o.call(this)},get:function(e){return null==e?o.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=w.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return w.each(this,e)},map:function(e){return this.pushStack(w.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(o.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:s,sort:n.sort,splice:n.splice},w.extend=w.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||g(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)n=a[t],a!==(r=e[t])&&(l&&r&&(w.isPlainObject(r)||(i=Array.isArray(r)))?(i?(i=!1,o=n&&Array.isArray(n)?n:[]):o=n&&w.isPlainObject(n)?n:{},a[t]=w.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},w.extend({expando:"jQuery"+("3.3.1"+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==c.call(e))&&(!(t=i(e))||"function"==typeof(n=f.call(t,"constructor")&&t.constructor)&&p.call(n)===d)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e){m(e)},each:function(e,t){var n,r=0;if(C(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},trim:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(C(Object(e))?w.merge(n,"string"==typeof e?[e]:e):s.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:u.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;o<a;o++)(r=!t(e[o],o))!==s&&i.push(e[o]);return i},map:function(e,t,n){var r,i,o=0,s=[];if(C(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&s.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&s.push(i);return a.apply([],s)},guid:1,support:h}),"function"==typeof Symbol&&(w.fn[Symbol.iterator]=n[Symbol.iterator]),w.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function C(e){var t=!!e&&"length"in e&&e.length,n=x(e);return!g(e)&&!y(e)&&("array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e)}var E=function(e){var t,n,r,i,o,a,s,u,l,c,f,p,d,h,g,y,v,m,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,E=ae(),k=ae(),S=ae(),D=function(e,t){return e===t&&(f=!0),0},N={}.hasOwnProperty,A=[],j=A.pop,q=A.push,L=A.push,H=A.slice,O=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},P="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",I="\\["+M+"*("+R+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+R+"))|)"+M+"*\\]",W=":("+R+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+I+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),F=new RegExp("^"+M+"*,"+M+"*"),_=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),z=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),X=new RegExp(W),U=new RegExp("^"+R+"$"),V={ID:new RegExp("^#("+R+")"),CLASS:new RegExp("^\\.("+R+")"),TAG:new RegExp("^("+R+"|[*])"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+W),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+P+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)Line truncated
+2 -2
View File
@@ -817,8 +817,8 @@ SockJS.prototype._connect = function() {
}
}
// calculate timeout based on RTO and round trips. Default to 5s
var timeoutMs = (this._rto * Transport.roundTrips) || 5000;
// calculate timeout based on RTO and round trips, compensate for potential nagle. Default to 5s.
var timeoutMs = (this._rto * Transport.roundTrips + 300) || 5000;
this._transportTimeoutId = setTimeout(this._transportTimeout.bind(this), timeoutMs);
debug('using timeout', timeoutMs);
+17 -2
View File
@@ -645,10 +645,14 @@ ul.dropdown-menu li a {
#files {
.gcode_files {
@padding: 5px;
@scrollBar: 10px;
@line-height: 20px;
padding-right: @scrollBar + 2px;
.scroll-wrapper {
overflow-x: hidden;
overflow-y: scroll;
height: 306px;
padding-right: 2px;
}
.entry {
padding: @padding;
@@ -670,6 +674,10 @@ ul.dropdown-menu li a {
color: #999;
}
.uploaded *[title] {
cursor: help;
}
.internal {
word-break: break-all;
}
@@ -888,6 +896,13 @@ ul.dropdown-menu li a {
}
}
#settings_appearance_managelanguagesdialog_list {
width: auto;
height: 300px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
}
#settings_appearance_managelanguagesdialog_emptylist {
overflow: hidden;
@@ -4,12 +4,12 @@
<p>Version <span class="version">{{ display_version }}</span></p>
<ul>
<li>Website: <a href="https://octoprint.org" target="_blank" rel="noreferrer noopener">octoprint.org</a></li>
<li>Community Forum: <a href="https://discourse.octoprint.org" target="_blank" rel="noreferrer noopener">discourse.octoprint.org</a></li>
<li>FAQ: <a href="https://faq.octoprint.org" target="_blank" rel="noreferrer noopener">faq.octoprint.org</a></li>
<li>Source Code: <a href="https://github.com/foosel/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint</a></li>
<li>Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
<ul class="fa-ul">
<li><i class="fa-li fa fa-home"></i> Website: <a href="https://octoprint.org" target="_blank" rel="noreferrer noopener">octoprint.org</a></li>
<li><i class="fa-li fa fa-users"></i> Community Forum: <a href="https://discourse.octoprint.org" target="_blank" rel="noreferrer noopener">discourse.octoprint.org</a></li>
<li><i class="fa-li fa fa-question-circle"></i> FAQ: <a href="https://faq.octoprint.org" target="_blank" rel="noreferrer noopener">faq.octoprint.org</a></li>
<li><i class="fa-li fa fa-book"></i> Documentation: <a href="http://docs.octoprint.org" target="_blank" rel="noreferrer noopener">docs.octoprint.org</a></li>
<li><i class="fa-li fa fa-github"></i> Source Code: <a href="https://github.com/foosel/OctoPrint" target="_blank" rel="noreferrer noopener">github.com/foosel/OctoPrint</a></li>
</ul>
<p>
@@ -49,7 +49,7 @@
</div>
<div class="modal-footer">
<button class="btn aboutlink" data-bind="click: about.show"><i class="fa fa-info-circle"></i> {{ _('About OctoPrint') }}</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">{{ _('Cancel') }}</button>
<button class="btn" data-bind="click: function() { cancelData() }" aria-hidden="true">{{ _('Close') }}</button>
<button class="btn btn-primary" data-bind="click: function() { saveData(undefined, $root.hide) }, enable: !exchanging(), css: {disabled: exchanging()}"><i class="fa fa-spinner fa-spin" data-bind="visible: sending"></i> {{ _('Save') }}</button>
</div>
</div>
@@ -132,15 +132,15 @@
</div>
</div>
<fieldset data-bind="visible: api_enabled">
<legend>Apikey</legend>
<legend>API Key</legend>
<div class="control-group">
<label class="control-label">{{ _('Current API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" readonly="readonly" data-bind="value: $root.users.editorApikey, valueUpdate: 'input', attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: $root.users.copyApikey, enable: $root.users.editorApikey"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: $root.users.copyApikey, css: {'disabled': !$root.users.editorApikey()}"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: function() { $root.users.confirmGenerateApikey(); }"><i class="fa fa-refresh"></i></a>
<a class="btn add-on btn-danger" title="Delete API Key" data-bind="click: function() { $root.users.confirmDeleteApikey(); }"><i class="fa fa-trash-o"></i></a>
<a class="btn add-on btn-danger" title="Delete API Key" data-bind="click: function() { $root.users.confirmDeleteApikey(); }, css: {'disabled': !$root.users.editorApikey()}"><i class="fa fa-trash-o"></i></a>
</div>
</div>
@@ -14,12 +14,12 @@
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-apiKey">{{ _('API Key') }}</label>
<label class="control-label" for="settings-apikey">{{ _('API Key') }}</label>
<div class="controls">
<div class="input-append input-block-level">
<input type="text" readonly="readonly" id="settings-apikey" data-bind="value: api_key, attr: {placeholder: '{{ _('N/A') }}'}">
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApiKey, enable: api_key"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApiKey, enable: api_key"><i class="fa fa-refresh"></i></a>
<a class="btn add-on" title="Copy API Key to clipboard" data-bind="click: copyApiKey, css: {'disabled': !api_key()}"><i class="fa fa-copy"></i></a>
<a class="btn add-on" title="Generate new API Key" data-bind="click: generateApiKey"><i class="fa fa-refresh"></i></a>
</div>
<span class="help-block">{{ _('Please note that changes to the API key are applied immediately, without having to "Save" first.') }}</span>
</div>
@@ -22,7 +22,7 @@
<div class="control-group" title="">
<label class="control-label" for="settings-appearanceLanguages">{{ _('Language Packs') }}</label>
<div class="controls">
<button class="btn" data-bind="click: showTranslationManager">{{ _('Manage...') }}</button>
<button class="btn" data-bind="click: showTranslationManager" id="settings-appearanceLanguages">{{ _('Manage...') }}</button>
</div>
</div>
<div class="control-group" title="">
@@ -61,7 +61,7 @@
<h4>{{ _('Available Language Packs') }}</h4>
<div data-bind="visible: languagePacksAvailable()">
<div id="settings_appearance_managelanguagesdialog_list" data-bind="slimScrolledForeach: translations.paginatedItems" style="height: 300px">
<div id="settings_appearance_managelanguagesdialog_list" data-bind="foreach: translations.paginatedItems">
<div class="entry">
<strong><a href="#" class="fa" data-bind="toggleContent: { class: 'fa-caret-right fa-caret-down', parent: '.entry', container: '.packs' }"><i class="fa fa-caret-down"></i> <span data-bind="text: $root.languagePackDisplay($data)"></span></a></strong>
<div class="packs">
@@ -1,18 +1,4 @@
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: feature_legacyPluginAssets" id="settings-legacyPluginAssets"> {{ _('Enable legacy plugin asset bundling') }} <span class="label label-info">Compatibility</span>
<span class="help-block">{% trans url="https://octoprint.org/blog/2017/12/01/heads-up-plugin-authors/" %}
Enable this, save and restart your server if you are running into issues with plugins with OctoPrint
1.3.6 or later that used to work with OctoPrint up to version 1.3.5. See <a href="{{ url }}">here</a>
for details on why this is happening. Note that this legacy flag will be removed in a future
OctoPrint version (currently planned for 1.3.8), so urge the authors of affected plugins to push
an update with a fix.
{% endtrans %}</span>
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
@@ -1,34 +1,54 @@
<form class="form-horizontal">
<h3>{{ _('Folders') }}</h3>
<div class="control-group">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.uploads, success: testFolderConfigOk.uploads}">
<label class="control-label" for="settings-folderUploads">{{ _('Upload Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_uploads" id="settings-folderUploads">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_uploads" id="settings-folderUploads">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('uploads'); }, enable: folder_uploads() && !testFolderConfigBusy(), css: {disabled: !folder_uploads() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.uploads() || testFolderConfigOk.uploads(), text: testFolderConfigText.uploads"></span>
</div>
</div>
<div class="control-group">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapse, success: testFolderConfigOk.timelapse}">
<label class="control-label" for="settings-folderTimelapse">{{ _('Timelapse Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
<div class="input-append input-block-level">
<input type="text" class="input-block-level" data-bind="value: folder_timelapse" id="settings-folderTimelapse">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapse'); }, enable: folder_timelapse() && !testFolderConfigBusy(), css: {disabled: !folder_timelapse() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapse() || testFolderConfigOk.timelapse(), text: testFolderConfigText.timelapse"></span>
</div>
</div>
<div class="control-group">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.timelapseTmp, success: testFolderConfigOk.timelapseTmp}">
<label class="control-label" for="settings-folderTimelapseTemp">{{ _('Timelapse Temp Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_timelapseTmp" id="settings-folderTimelapseTemp">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('timelapseTmp'); }, enable: folder_timelapseTmp() && !testFolderConfigBusy(), css: {disabled: !folder_timelapseTmp() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.timelapseTmp() || testFolderConfigOk.timelapseTmp(), text: testFolderConfigText.timelapseTmp"></span>
</div>
</div>
<div class="control-group">
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.logs, success: testFolderConfigOk.logs}">
<label class="control-label" for="settings-folderLogs">{{ _('Logs Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_logs" id="settings-folderLogs">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_logs" id="settings-folderLogs">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('logs'); }, enable: folder_logs() && !testFolderConfigBusy(), css: {disabled: !folder_logs() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.logs() || testFolderConfigOk.logs(), text: testFolderConfigText.logs"></span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="settings-watchedLogs">{{ _('Watched Folder') }}</label>
<div class="control-group" data-bind="css: {error: testFolderConfigBroken.watched, success: testFolderConfigOk.watched}">
<label class="control-label" for="settings-folderWatched">{{ _('Watched Folder') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: folder_watched" id="settings-folderWatched">
<div class="input-append input-block-level">
<input type="text" data-bind="value: folder_watched" id="settings-folderWatched">
<a class="btn add-on" data-bind="click: function() { testFolderConfig('watched'); }, enable: folder_watched() && !testFolderConfigBusy(), css: {disabled: !folder_watched() || testFolderConfigBusy()}"><i class="fa fa-spinner fa-spin" data-bind="visible: testFolderConfigBusy"></i> {{ _('Test') }}</a>
</div>
<span class="help-block" data-bind="visible: testFolderConfigBroken.watched() || testFolderConfigOk.watched(), text: testFolderConfigText.watched"></span>
</div>
</div>
<div class="control-group">
@@ -44,15 +64,15 @@
<p>{{ _('If the free disk space falls below these thresholds, OctoPrint will warn the user.') }}</p>
<div class="control-group" title="{{ ('Threshold after which to warn about the remaining free space on disk.') }}">
<label class="control-label" for="settings.serverDiskusageWarning">{{ _('Warning') }}</label>
<label class="control-label" for="settings-serverDiskusageWarning">{{ _('Warning') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_warning_str" id="settings-serverDiskusageWarning">
</div>
</div>
<div class="control-group" title="{{ ('Threshold after which to consider remaining free space on disk as critical.') }}">
<label class="control-label" for="settings.serverDiskusageCritical">{{ _('Critical') }}</label>
<label class="control-label" for="settings-serverDiskusageCritical">{{ _('Critical') }}</label>
<div class="controls">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str">
<input type="text" class="input-mini text-right" data-bind="value: server_diskspace_critical_str" id="settings-serverDiskusageCritical">
</div>
</div>
@@ -7,10 +7,10 @@
</div>
</div>
<div class="control-group" title="{{ _('Maximum size the GCodeViewer autoloads the file for preview') }}">
<label class="control-label" for="settings-gcodeviewer">{{ _('GCode Visualizer file size threshold') }}</label>
<label class="control-label" for="settings-featureSizeThreshold">{{ _('GCode Visualizer file size threshold') }}</label>
<div class="controls">
<div class="input-append">
<input type="text" class="input-mini text-right" data-bind="value: feature_sizeThreshold_str">
<input type="text" class="input-mini text-right" data-bind="value: feature_sizeThreshold_str" id="settings-featureSizeThreshold">
</div>
<span class="help-inline">{{ _('on desktop')}}</span>
</div>
Loaded 100 of 160 files, more files were not shown because too many files have changed in this diff. Show more