Compare commits

...
522 Commits
Author SHA1 Message Date
Gina Häußge 112a8b9c8b Merge branch 'rc/maintenance' 2018-12-10 13:01:23 +01:00
Gina Häußge 98b692d845 Preparing release of 1.3.10 2018-12-10 12:44:25 +01:00
Gina Häußge a657ebd528 staging/maintenance is now 1.3.10rc5.dev 2018-12-03 14:16:31 +01:00
Gina Häußge e628aedbc1 Preparing release of 1.3.10rc4 2018-12-03 12:42:28 +01:00
Gina Häußge 38fce1665b backup: signal restore done before reboot 2018-11-30 20:07:18 +01:00
Gina Häußge f51a98768c backup: more feedback during restore
The upload of a backup can take a while, so pop up the work dialog as
soon as that starts, not only when it is finished.
2018-11-30 20:06:57 +01:00
Gina Häußge 4d04c323f6 backup: use base version for version check 2018-11-30 20:06:24 +01:00
Gina Häußge 94116bfd53 backup: fix on_restore_failed calls 2018-11-30 18:33:58 +01:00
Gina Häußge a05761e63f backup: better error logging 2018-11-30 18:29:55 +01:00
Gina Häußge 89469d38ae printer safety: Fix localization of warning 2018-11-30 17:06:07 +01:00
Gina Häußge bd2616e888 backup: exclude generated, logs & watched
We don't need these in the backup, and in fact they only make things
more bloated and/or complicated.
2018-11-30 16:53:26 +01:00
Gina Häußge 02e996436d backup: restore is not supported on windows
Sadly the stupid file locking of windows makes it impossible to
hot swap the config directory. In order to support windows a two step
approach would be needed. Maybe at a later date, currently simply not
worth the effort tbh considering how seldomly windows is used as OS for
OctoPrint.
2018-11-30 16:53:19 +01:00
Gina Häußge a3f2e0b56c backup: fix plugin compatibility check on restore
Fixes #2920
2018-11-30 16:21:58 +01:00
Gina Häußge d60cab1962 staging/maintenance is now 1.3.10rc4.dev 2018-11-28 14:56:39 +01:00
Gina Häußge b01e327f9d Preparing release of 1.3.10rc3 2018-11-28 12:56:02 +01:00
Gina Häußge 09af2813d0 Add dedicated issue templates 2018-11-27 14:21:13 +01:00
Gina Häußge 13260fa219 tracking: file path instead of just name in print events
Closes #2908
2018-11-26 14:10:03 +01:00
Gina Häußge 8292408c79 Remove image from changelog, replace with text
Closes #2909
2018-11-26 12:05:58 +01:00
Gina Häußge 9165f83084 printer safety: Mark stock Micro3D fw as unsafe
See https://github.com/donovan6000/iMe/issues/67#issuecomment-441454163
2018-11-26 10:27:20 +01:00
Gina Häußge c2ef371089 Docs: add documentation for some config params 2018-11-23 11:12:40 +01:00
Gina Häußge ac129a2576 Only patch sarge's async on python 2 2018-11-22 13:10:59 +01:00
Gina Häußge db8d420860 Decorator for sarge that translate async to async_
Should work around issues with third party plugins that haven't yet
adapted.
2018-11-22 12:37:28 +01:00
Gina Häußge 7d7cbb1760 Some reordering in the settings 2018-11-21 16:14:23 +01:00
Gina Häußge 89979f1bee Revert "Hardening against bad plugins"
Making on_after_startup asynchronous unearths some odd issue that causes
subsequent callback calls to duplicate. It might just be PyCharm's
debugger (disabling it makes the problem go away and I so far couldn't
reproduce it without it), but just in the case that I introduced some
weird race condition with this _async approach I'm removing it. I'd
rather have badly implemented plugins break the startup then the startup
being inherently broken from the get go.

Added a couple more warnings in the docs though.
2018-11-21 16:14:06 +01:00
Gina Häußge bd241e8e6c backup: allow zip64 2018-11-21 12:19:04 +01:00
Gina Häußge 7939b0ae4d backup: better error reporting 2018-11-21 12:10:03 +01:00
Gina Häußge 6b57ba2d7d printer_safety: detect iMe on Micro3D
See donovan6000/iMe#67
2018-11-20 12:42:52 +01:00
Gina Häußge 2c5465f9a6 Got rid of an unused import 2018-11-20 12:42:50 +01:00
Gina Häußge 1565129cfb docs: warning about blocking ops in some plugin callbacks 2018-11-20 12:42:49 +01:00
Gina Häußge b8d4a58207 SWU: remove one thread level
on_after_startup now runs in its own thread, no need to spawn yet
another.
2018-11-20 12:42:43 +01:00
Gina Häußge 900f03dc8a SWU: add a timeout to the wait on environment info 2018-11-20 12:24:50 +01:00
Gina Häußge 0c4c4a9d18 Hardening against bad plugins
We don't want on_after_startup or on_event handling to get blocked by
some rogue plugin that decides to block or outright kill the thread.
2018-11-20 12:19:17 +01:00
Gina Häußge ff4ed38329 Track user logout on socket 2018-11-19 15:24:12 +01:00
Gina Häußge 5f78ab7b73 Register for plugin messages on socket connect
Second part of the fix for #2898
2018-11-19 15:22:45 +01:00
Gina Häußge 6556d555bd forcelogin: Keep message backlog while not authed
First part of the fix for #2898
2018-11-19 15:22:33 +01:00
Gina Häußge d318ff82b8 More error resilience in the local ip check
Should solve #2897
2018-11-16 13:57:11 +01:00
Gina Häußge ff53a826f9 tracking: Fix link of plugin in plugin manager 2018-11-16 13:19:31 +01:00
Gina Häußge d79e777911 Update german translation 2018-11-15 14:42:48 +01:00
Gina Häußge 335e635ec7 printer_safety_check: Make a text translateable 2018-11-15 14:17:06 +01:00
Gina Häußge a5754a8552 pi_support: Add link to the new FAQ entry 2018-11-15 14:16:27 +01:00
Gina Häußge a8c91ff6ba pi_support: Better wording in popover & highlight current 2018-11-15 12:57:02 +01:00
Gina Häußge 6285fd8010 Allow dynamic values in ko popover binding 2018-11-15 12:40:03 +01:00
Gina Häußge 799aedcaed staging/maintenance is now 1.3.10rc3.dev 2018-11-13 16:16:43 +01:00
Gina Häußge de42ce73f7 Preparing release of 1.3.10rc2 2018-11-13 12:43:06 +01:00
Gina Häußge 962e09906e tracking: Fix translatability of a message 2018-11-13 12:42:31 +01:00
Gina Häußge f607f55683 printer_safety_check: Detect Ender 3 stock fw
As reported in https://discourse.octoprint.org/t/thermal-runaway-protection-absent-on-creality-ender-3/2787
2018-11-13 11:17:24 +01:00
Gina Häußge 1b45047826 tracking: wizard changes
* spinners for the enable/disable buttons
  * error handler for persisting the decision that unlocks the wizard

Might help to work around issues less than a hand full of people have
now observed where the wizard's buttons are non functional but the
wizard itself is active and blocking.

More data needed to reproduce and debug the core issue though.
2018-11-12 15:23:17 +01:00
Gina Häußge edd4d90b12 tracking: tracking.js -> usage.js
To work around some ad blockers that might block this otherwise - which
is kinda funny since the js file doesn't do any tracking, it just
makes the setup wizard for the opt-in functional 🤦‍♀️
2018-11-12 14:33:43 +01:00
Gina Häußge 0a3ad8a880 tracking: add time & reason for failure to print_failed
(cherry picked from commit b7e373c)
2018-11-12 14:33:43 +01:00
Gina Häußge 82615791a2 Add time & reason for failure to PrintFailed event
(cherry picked from commit dae0264)
2018-11-12 14:33:42 +01:00
Gina Häußge 2b5af2c36a Add docs for octoprint.util.commandline 2018-11-09 18:16:57 +01:00
Gina Häußge b2e50e13d4 Blacklist broken regex version 2018-11-08 15:54:05 +01:00
Gina Häußge cb4404a833 Merge branch 'pr/2878' into staging/maintenance 2018-11-08 15:50:13 +01:00
Gina Häußge 38bb81cfe7 tracking: add throttle events, slightly change throttle payload
Also adjusted helper signature in pi_support plugin slightly.

Addon to #2878
2018-11-08 15:49:11 +01:00
Gina Häußge 1667f9bd52 Fix bug introduced in 4caf4ef09 2018-11-08 14:00:48 +01:00
Gina Häußge 1ec61a9fe6 Give the favicon mask SVG width and height attrs
Otherwise it won't render correctly in Firefox due to drawImage silently
failing, see also https://bugzilla.mozilla.org/show_bug.cgi?id=700533

Closes #2879
2018-11-08 13:42:19 +01:00
tedder 98c84b6bb9 fix test, match dict 2018-11-08 01:34:45 +00:00
tedder 76f48b3b13 PR feedback: throttle state and uuid
- add a way to get the raw value only from throttle state (glad I already plumbed it into the object!)
- add warning about not sending uuid, modify the log entry too
2018-11-08 01:29:15 +00:00
Gina Häußge 8596ae5c4a SWU: Make sure check providers are in the correct format
Just in case there's some odd data in `config.yaml` as reported in https://github.com/foosel/OctoPrint/issues/2871#issuecomment-436507623
2018-11-07 11:10:31 +01:00
tedder c1482eaacd add throttle_state to tracking
- weave the throttle_state through pi_support and tracking. This should come in handy to see how many throttled Pis are out there, as well as if it is correllated with canceled prints.
- upgraded disclosure of tracking information so it shows as INFO-level in the logs and all the information is dumped. If tracking.octoprint.org gets it, I should have it too :)
2018-11-06 15:37:45 -08:00
Gina Häußge e23fe4a925 forcelogin: Fix issue when running with acl disabled
Closes one variant of #2876
2018-11-06 17:34:01 +01:00
Gina Häußge 2f08b90200 Merge branch 'master' into staging/maintenance 2018-11-06 15:56:33 +01:00
Gina Häußge 68ca2c5e51 Pin regex dependency to last known working version
See #2874 and https://bitbucket.org/mrabarnett/mrab-regex/issues/301/typeerror-character-mapping-must-return
2018-11-06 15:52:41 +01:00
Gina Häußge 343195477b Fix connection fail if fw doesn't send start
Closes #2872
2018-11-06 14:47:39 +01:00
Gina Häußge 4caf4ef09b Fix GCODE viewer not being able to load files
Side effect of the ForcedLogin plugin and a bug in
get_flask_user_from_request.

Closes #2873
2018-11-06 14:02:49 +01:00
Gina Häußge 0325628693 staging/maintenance is now 1.3.10rc2.dev 2018-11-06 12:29:28 +01:00
Gina Häußge e14c00f135 Revert "Updated several dependencies to current version"
This reverts commit 4ed5f7e

The updates cause issues on very old python environments (distribute
instead of setuptools, e.g. OctoPi 0.12) due to new package formats.

We'll postpone them to 1.3.11, since OctoPrint 1.3.10 will then refuse
to upgrade in such environments anyhow.
2018-11-05 14:25:10 +01:00
Gina Häußge b0a4a49f99 Changelog for 1.3.10rc1 2018-11-05 13:18:05 +01:00
Gina Häußge 5b4839369e appkeys: Probe endpoint to check for workflow support
Also adjusted docs and js client lib accordingly.
2018-11-05 12:50:05 +01:00
Gina Häußge 1ff02b9f1c Update bundled German translation 2018-11-05 11:59:48 +01:00
Gina Häußge e2c1fa3d43 Appkeys: request creation should respond with 201 2018-11-02 17:04:58 +01:00
Gina Häußge 39a466e316 Appkeys: Make timeout thread safe 2018-11-02 12:53:30 +01:00
Gina Häußge 9e940eacc3 Merge branch 'fix_appkey_orphan_dialogs' of https://github.com/fieldOfView/OctoPrint into pr/2869 2018-11-02 12:27:16 +01:00
Gina Häußge 2e38f237de Fix cancel snippet for shared nozzle setups
See https://discourse.octoprint.org/t/prusa-mmu2-how-to-properly-configure/4937/
2018-11-02 12:20:05 +01:00
fieldOfView 7f36ffdafd Expire request_access when the client stops polling 2018-11-02 11:04:06 +01:00
Gina Häußge 39b2da3230 Merge pull request #2868 from gdombiak/extrude_speed2
Documentation fixed and extrusion speed value check
2018-11-02 10:52:42 +01:00
fieldOfView c489829efb Add myself to AUTHORS.md
because it's a requirement for a PR
2018-11-02 09:31:56 +01:00
fieldOfView e30e129e2a Close request_access dialogs on other open connections when a decision is made
Once a decision is made on one connection (browser window), dialogs on other connections are no longer relevant.
2018-11-02 09:22:30 +01:00
Gaston Dombiak 32d5b25013 Removed unnecessary variable initialization 2018-11-01 21:44:42 -07:00
Gaston Dombiak 6227a0dfb9 1) Fixed documentation about speed unit and 2) extrusion speed is now limited to printer profile max value 2018-10-31 20:45:56 -07:00
Gina Häußge e234c6146e Better detection of ipv6 support
Apparently socket.has_ipv6 doesn't actually do what it says in the docs
(state whether the underlying platform supports ipv6). It returns True
even when ipv6 has manually been disabled for whatever reason. So we
will no longer trust this but instead attempt to actually create a v6
socket and only if that succeeds assume that v6 is indeed supported on
the platform.
2018-10-31 13:39:54 +01:00
Gina Häußge c146731e5a Merge pull request #2865 from gdombiak/extrude_speed
Extrude speed
2018-10-31 11:58:28 +01:00
Gina Häußge 5ee242be4a Fix doc bug: mm/s => mm/min 2018-10-31 11:54:17 +01:00
Gaston Dombiak 556878a774 Merge branch 'maintenance' into extrude_speed 2018-10-30 19:09:05 -07:00
Gaston Dombiak 00aa4876e9 Added support to specify extrude/retract speed. Only at REST API. No UI changes were made 2018-10-30 19:01:20 -07:00
Gina Häußge e5e8581f9a Detect invalid test setups in settings tests
Should prevent future cases of the chainmap issue observed in #2828 and
maybe also #2829
2018-10-30 17:16:48 +01:00
Gina Häußge 95a9f84b39 Reflect current connection in connection panel
Implements #2859
2018-10-30 15:56:36 +01:00
Gina Häußge 371f1a818f tracking: add uuid to filename hash in print event tracking
We don't need to be able to identify the same file across multiple
instances, just repeated prints on the same instance.

Thanks to @scoder for the suggestion.
2018-10-30 13:36:32 +01:00
Gina Häußge 4ed5f7ed28 Updated several dependencies to current version
Werkzeug update required a flask monkey patch since we can't update
flask due to it depending on a newer jinja version which is backwards
incompatible and hence would cause issues with third party plugins.

Also added notes to the dependencies that are found to be hard to update
so that future release preparations don't require to figure out the
"why not" all over again.
2018-10-30 13:31:36 +01:00
Gina Häußge 4eb81aae9d cura: workaround for broken placeholders in profiles
Apparently some exports contain ?print_temperature? instead of
{print_temperature} style placeholders? At least that was observed in
the example in #2629.

This fixes such placeholders.
2018-10-29 17:41:57 +01:00
Gina Häußge dafa4c97ad cura: fix extruder count for start gcode selection
Fixes #2629
2018-10-29 17:30:49 +01:00
Gina Häußge 0268cafa90 Reflect current port/baudrate/profile in connection tab
Fixes #2740
2018-10-29 13:56:34 +01:00
Gina Häußge a5caac8d38 Disable external heatup detection for teacup fw
Implements #2854
2018-10-29 11:55:37 +01:00
Gina Häußge 7ca9d56327 Merge branch 'improve/appauth' into maintenance 2018-10-29 11:45:05 +01:00
Gina Häußge d9323b7172 docs: new clientjs asset type 2018-10-29 11:44:27 +01:00
Gina Häußge 8f6d67195d appkeys: clean up pendings older than 10min & meta data 2018-10-29 11:42:12 +01:00
Gina Häußge 342d526a51 appkeys: finalize docs 2018-10-29 11:08:00 +01:00
Gina Häußge d7c5f57c98 appkeys: fix app bulk selection 2018-10-29 10:32:13 +01:00
Gina Häußge d89ca38ee8 WIP: Docs for appkeys plugin 2018-10-29 10:30:48 +01:00
Gina Häußge cb969be403 docs: clarify that user name == user id 2018-10-24 09:52:26 +02:00
Gina Häußge 7cb649c303 docs: fix auth message docs on push API
Thanks @gdombiak for the heads-up
2018-10-24 09:48:00 +02:00
Gina Häußge 6d7d365b27 appkeys: bulk delete & fixed sorting 2018-10-23 13:47:54 +02:00
Gina Häußge 8ad720e554 Merge remote-tracking branch 'origin/improve/appauth' into improve/appauth
# Conflicts:
#	src/octoprint/plugins/appkeys/__init__.py
#	src/octoprint/plugins/appkeys/static/clientjs/appkeys.js
#	src/octoprint/plugins/appkeys/static/js/appkeys.js
#	src/octoprint/plugins/appkeys/templates/appkeys_usersettings.jinja2
#	src/octoprint/server/util/flask.py
2018-10-22 18:53:28 +02:00
Gina Häußge 37190da2d6 Merge branch 'maintenance' into improve/appauth
# Conflicts:
#	src/octoprint/server/util/flask.py
2018-10-22 18:50:32 +02:00
Gina Häußge 2746139fa6 appkeys: central settings page with all keys 2018-10-22 18:44:55 +02:00
Gina Häußge c9f10ae723 printer_safety_check: docs update 2018-10-22 17:42:31 +02:00
Gina Häußge 202006149c forcelogin: documentation, incl. newly added hooks 2018-10-22 17:38:48 +02:00
Gina Häußge 671973062e announcements: add missing images for docs 2018-10-22 16:43:07 +02:00
Gina Häußge 1d15c2a176 backup: docs & small changes in wording 2018-10-22 16:42:47 +02:00
Gina Häußge 5e490ec7fd Revert "Update some dependencies"
This reverts commit 6d2be17
2018-10-22 16:19:42 +02:00
Gina Häußge 1889a40241 Merge branch 'improve/swuCheckEnvironment' into maintenance 2018-10-22 13:07:59 +02:00
Gina Häußge 6d2be1743a Update some dependencies
There are more updates, but they introduce backwards compatibility
issues that would hurt third party plugins, so we need to find
workarounds for these first - or trigger a grace period.
2018-10-22 13:02:57 +02:00
Gina Häußge e9e4adf09b tracking: flask.ext.babel => flask_babel 2018-10-22 13:01:42 +02:00
Gina Häußge 535ad6eae6 Merge pull request #2858 from gdombiak/issue_2850
Fixed unsafe write_message call from another thread
2018-10-22 11:47:16 +02:00
Gaston Dombiak c4167a82c5 Fixed unsafe write_message call from another thread.
Issue #2850
2018-10-21 00:58:14 -07:00
Gina Häußge 087a9ece2c Make sure to show only one external address warning notification at once 2018-10-19 17:00:42 +02:00
Gina Häußge b77380a8ac Add logging for active/passive login 2018-10-19 16:50:58 +02:00
Gina Häußge 169275b052 Fix wrong position of parentheses, add unit tests 2018-10-19 16:39:18 +02:00
Gina Häußge 757dfcf5c7 unmap ipv6 mapped v4 addresses on lan check 2018-10-19 16:19:51 +02:00
Gina Häußge 8e39eac207 discovery: start name counter at 1
We want our second instance with the same name to show up as (2) not (1)
2018-10-19 14:17:16 +02:00
Gina Häußge 9e48b8ab65 make sure to strip comments from address 2018-10-19 14:13:33 +02:00
Gina Häußge 36b07b2337 discovery: enumerate zeroconf service names on collision
Fixes #2852
2018-10-19 13:58:37 +02:00
Gina Häußge e57c46fb67 Missed something in yesterday's changes to contrib guide 2018-10-19 13:34:13 +02:00
Gina Häußge df8226b8c5 Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
    new features
  * suggest getting in touch on the forum for larger changes
2018-10-19 13:34:12 +02:00
Gina Häußge 2f89082df2 Missed something in yesterday's changes to contrib guide 2018-10-19 13:14:52 +02:00
Gina Häußge e0943527d6 Merge pull request #2847 from eyal0/always_babel_extract
Remove requirement to have messages.pot to use babel_extract
2018-10-18 18:36:42 +02:00
Gina Häußge 108db045ce Small changes to the contribution guidelines
* allow PRs against `maintenance` branch for improvements and small
    new features
  * suggest getting in touch on the forum for larger changes
2018-10-18 18:06:01 +02:00
Eyal Soha 025986794f Remove requirement to have messages.pot to use babel_extract 2018-10-18 11:52:01 -04:00
Gina Häußge ac2354907a Remove some trailing whitespace 2018-10-18 17:33:08 +02:00
Gina Häußge 7b5d2e3e0c Allow whitespace after : in M114 responses
Closes #2839
2018-10-18 17:32:32 +02:00
Gina Häußge efa556a812 Announcements: forgot to git add the new doc page -_- 2018-10-15 17:23:21 +02:00
Gina Häußge 7f9764c386 Announcements: fix a bug & add docs 2018-10-15 17:11:07 +02:00
Gina Häußge e95e546c08 Appkey: Copy key to clipboard 2018-10-15 12:48:41 +02:00
Gina Häußge b0e7df47a6 Appkeys: Add key persistence 2018-09-29 15:00:28 +02:00
Gina Häußge 257fc0d1cd Appkeys: allow fetching of all keys
Also added TODO list ;)
2018-09-29 15:00:27 +02:00
Gina Häußge 3fe2b611bc Appkeys: fix template config 2018-09-29 15:00:27 +02:00
Gina Häußge d6c63a5cb9 appauth -> appkeys 2018-09-29 15:00:27 +02:00
Gina Häußge ad8205c386 AppAuth: workflow fully implemented & client lib 2018-09-29 15:00:27 +02:00
Gina Häußge 6efd4dfd08 New options for confirmation dialog
* oncancel: callback to call when cancel button is pressed
  * noclose: don't allow dismissing/closing the dialog without having
    chosen to proceed or cancel
2018-09-29 15:00:27 +02:00
Gina Häußge 469bf844ee Clientlib: support operation without api key 2018-09-29 15:00:27 +02:00
Gina Häußge 4f58c64881 New asset type "clientjs" for client library bits 2018-09-29 15:00:27 +02:00
Gina Häußge b428faacc8 Appauth plugin: WIP 2018-09-29 15:00:26 +02:00
Gina Häußge 4e3adcc3f3 Add no_firstrun_access decorator 2018-09-29 15:00:26 +02:00
Gina Häußge f88147003c Repetier firmware reports fatal errors with another prefix 2018-09-29 14:54:39 +02:00
Gina Häußge bbbe85f737 Multiline fatal error parsing for Marlin 2018-09-29 14:38:54 +02:00
Gina Häußge fc97d0b424 Virtual: simulate some fatal errors 2018-09-29 14:38:35 +02:00
Gina Häußge b054ec47ad Special handling for fatal errors
If the firmware locks up it doesn't make sense to stay connected to
it even if we are supposed to only cancel an ongoing print.
2018-09-29 13:28:09 +02:00
Gina Häußge 87e7a19fdd Forcelogin: Support theming via custom hook 2018-09-28 17:57:05 +02:00
Gina Häußge fed257b5d8 Forcelogin: Fix spinner 2018-09-28 17:19:31 +02:00
Gina Häußge e53ae8cd56 Forcelogin: Access to settings isn't needed either 2018-09-28 17:15:37 +02:00
Gina Häußge a9f76dd1a3 Forcelogin: allow socket when ACL isn't setup yet 2018-09-27 18:47:00 +02:00
Gina Häußge 6bc5b8a7a9 Forcelogin: lock down sockjs socket as well 2018-09-27 18:44:03 +02:00
Gina Häußge cb9bedb6a0 Add hooks to control sockjs registrations and messages 2018-09-27 18:43:46 +02:00
Gina Häußge 5ff790048d Fix unit tests 2018-09-26 15:52:10 +02:00
Gina Häußge f32ea65b2c Support EMERGENCY_PARSER & use M108 on cancel (unless disabled)
Implements #1504
2018-09-26 15:29:15 +02:00
Gina Häußge 1f957e1ee2 forcelogin: disable while ACL hasn't been configured 2018-09-26 15:21:51 +02:00
Gina Häußge 32be5ca87c Better error handling if file becomes unreadable
Implements #2674
2018-09-24 16:50:14 +02:00
Gina Häußge 8876ab0ce5 SWU: Fix version output of CLI update message 2018-09-21 18:43:20 +02:00
Gina Häußge ad8910354c SWU: Fix CLI updating
Closes #2712
2018-09-21 18:41:22 +02:00
Gina Häußge e8d6a9b221 Only reset timeout to busy once it has been set on printer
Should fix #2752
2018-09-21 18:25:58 +02:00
Gina Häußge f3cfe2ba48 Virtual: add long running pseudo G33
Useful for testing busy protocol on commands.
2018-09-21 18:25:58 +02:00
Gina Häußge d2ecb0a28f Merge pull request #2827 from tedder/docfix_sdReleativePath_maint
spellfix 'sdReleativePath'
2018-09-21 18:05:21 +02:00
Ted Timmons 134ee77e4a spellfix 'sdReleativePath'
It's only misspelled in the docs, it is correct in the code.
2018-09-21 08:45:53 -07:00
Gina Häußge 10f3f72b9c Unit tests: Fix duplicated test method
Closes #2805
2018-09-21 14:35:20 +02:00
Gina Häußge 78b6d3a5e2 Merge pull request #2800 from gerfderp/patch-1
Documentation conjugation fix.
2018-09-18 17:18:18 +02:00
Gina Häußge a920c4fe21 Merge pull request #2806 from tedder/201809_rewrite_test_get_recovery
rewrite test_get_recovery_data
2018-09-18 17:12:27 +02:00
Gina Häußge 52468e7e1c Merge pull request #2802 from tedder/201809_temperature_regex_update
201809 temperature regex update
2018-09-18 17:10:37 +02:00
Gina Häußge 9112a800c8 Add forcelogin plugin 2018-09-14 20:06:32 +02:00
Gina Häußge 177d235b29 Make a helper method public 2018-09-14 20:06:32 +02:00
Gina Häußge 2de2dc7c31 Allow further access restriction on API and Tornado routes through plugin hooks 2018-09-14 20:06:32 +02:00
Paul de Vries 8074a06d33 Use .fail instead of .error
.error() was removed in jQuery 3 and is throwing errors when logging out,
use .fail instead
2018-09-09 11:37:38 +00:00
Gina Häußge 75c801d63f Unit tests for is_lan_address
Also fixed a bug in subnet creation in the process.
2018-09-04 14:01:31 +02:00
Gina Häußge ed07764f09 Put warnings into core/first run wizard 2018-09-04 12:00:07 +02:00
Gina Häußge a929100889 Allow to disable ip check & define trusted subnets
Will need manually editing config.yaml for the time being. Someone who
is not able to edit a yaml file should not be able to disable the
warning.
2018-09-04 09:26:29 +02:00
Gina Häußge 286376321c Detect connections to the UI from external ips
Show warning to protect the innocent who don't know better than to
port forward.

Warning is ignorable (per browser) to allow users who know what they are
doing to easily get rid of it. If you don't know what you are doing and
also actively ignore THIS warning I really can't help you anymore.
2018-09-03 21:23:08 +02:00
Gina Häußge 4a36a3eed2 Appkeys: Add key persistence 2018-09-03 18:38:36 +02:00
tedder 8bf9b8650d rewrite test_get_recovery_data
I was pulling my hair out with some py3 compatability, so .. I ended up basically rewriting it. Basically a big refactor, still compatible with py2.
2018-09-01 22:07:41 -07:00
tedder d6da819cd6 add unit tests for temperature regexes 2018-09-01 10:46:29 -07:00
tedder 2fbc81604a update temperature regex
It exists in three locations, so I'm making sure they are all synced. This ensures the MP Mini Delta flavor of Marlin is properly masked; I have that and a Prusa mk3 to verify against.

This came out of this thread:
https://discourse.octoprint.org/t/temperature-message-filter-doesnt-filter-temperature-messages/3643
2018-09-01 08:39:25 -07:00
Gina Häußge 2ca63febee Appkeys: allow fetching of all keys
Also added TODO list ;)
2018-08-31 20:45:16 +02:00
Gina Häußge 224674f27e Appkeys: fix template config 2018-08-31 20:35:16 +02:00
Gina Häußge 2f1d71a98c appauth -> appkeys 2018-08-31 20:22:40 +02:00
gerfderp 7366110f07 Update helpers.rst
fixing conjugation
2018-08-29 14:59:00 -07:00
Gina Häußge e5eb72cbfb Docs: Make it extra crystal clear to use a VPN 2018-08-29 15:49:09 +02:00
Gina Häußge b0028cd3fb AppAuth: workflow fully implemented & client lib 2018-08-28 22:05:28 +02:00
Gina Häußge 2343caea30 New options for confirmation dialog
* oncancel: callback to call when cancel button is pressed
  * noclose: don't allow dismissing/closing the dialog without having
    chosen to proceed or cancel
2018-08-28 22:04:34 +02:00
Gina Häußge 61d037f188 Clientlib: support operation without api key 2018-08-28 22:02:40 +02:00
Gina Häußge 2a79d9183a New asset type "clientjs" for client library bits 2018-08-28 22:02:18 +02:00
Gina Häußge 5dbc88b6f2 Detect scrolling direction in terminal
Only disable autoscroll if we are scrolling up.
2018-08-27 15:58:15 +02:00
Gina Häußge 83876806db Force terminal scroll on browser tab activation
Possible fix for #2774
2018-08-27 15:57:59 +02:00
Gina Häußge 5a5785be4a Appauth plugin: WIP 2018-08-24 11:59:23 +02:00
Gina Häußge 25cd4f8201 Add no_firstrun_access decorator 2018-08-24 11:58:56 +02:00
Gina Häußge 2d72a52338 Backup: Fix a copy paste error 2018-08-22 17:58:29 +02:00
Gina Häußge b5a161594d Fix documentation error
We return 403 on a wrong API key, not 401 - 401 causes issues with Basic Auth setups as reported
in #2297 and hence fixed in b1f9e070a4.

Closes #2706
2018-08-20 14:25:28 +02:00
Gina Häußge a24363c4b0 Fix API error when accessing sdcard file details
Closes #2705
2018-08-20 14:04:09 +02:00
Gina Häußge 524562527e Cura: Error message if profile import fails
See #2769
2018-08-20 12:58:27 +02:00
Gina Häußge 26856d052f Fix wrong min/max parameter being used for timeouts
Closes #2780
2018-08-20 11:54:27 +02:00
Gina Häußge 17f8817b78 Backup: Got rid of caching plans 2018-08-17 15:06:07 +02:00
Gina Häußge 4eb1d2bf80 Backup: Check compatibility when installing plugins from repo during restore 2018-08-17 15:00:09 +02:00
Gina Häußge 62120affae PMGR: Finalize extraction of is_os_compatible into octoprint.util.platform 2018-08-17 14:13:01 +02:00
Gina Häußge 66b501cfaa Backup: Show list of plugins unknown during restore in settings 2018-08-16 17:50:58 +02:00
Gina Häußge 140bf9aa5a Backup: Fix recording list of uninstallable plugins 2018-08-16 15:20:11 +02:00
Gina Häußge 711ca457f2 Backup: WIP of handling unknown plugins 2018-08-16 09:05:45 +02:00
Gina Häußge 07ae4ffe14 Backup: Delete bck from earlier restore on startup 2018-08-14 19:56:17 +02:00
Gina Häußge 3800b21e69 Bkacup: Fix CLI logging of exceptions 2018-08-14 19:48:58 +02:00
Gina Häußge 196b152ec4 Backup: Remove left over parameter 2018-08-14 19:28:36 +02:00
Gina Häußge 970810dc92 Backup: Move into "OctoPrint" sub section 2018-08-14 19:28:11 +02:00
Gina Häußge 4fec14197b Backup: Some UI changes & confirmations 2018-08-14 19:27:47 +02:00
Gina Häußge b354334a2e Backup: Add log window during restore 2018-08-13 19:02:50 +02:00
Gina Häußge a934750504 Backup: Upload of backup to restore works 2018-08-10 20:46:30 +02:00
Gina Häußge 9dc29689f4 Backup: Restore now seems to work 2018-08-10 11:58:06 +02:00
Gina Häußge 8518b40b5f Backup: WIP on restore function
Plugin installation is still challenging.
2018-08-09 12:45:27 +02:00
Gina Häußge aabd624f88 Backup: WIP on restore 2018-08-07 15:14:12 +02:00
Gina Häußge 6ae88ab8c6 Backup: subfolder for basedir contents 2018-08-06 13:43:17 +02:00
Gina Häußge 6251031d6e Backup works, incl management UI 2018-08-06 13:35:02 +02:00
Gina Häußge 249b3f442b Slight refactoring 2018-08-06 13:34:30 +02:00
Gina Häußge ff6012bb00 WIP: Backup & Restore plugin 2018-08-03 17:20:28 +02:00
Gina Häußge a137946e3a Remove setup_requires - it's incompatible to pip 2018-07-28 23:36:28 +02:00
Gina Häußge 909dd551d6 Specify support python versions 2018-07-28 23:30:43 +02:00
Gina Häußge 687b449207 SWU: Prevent auto updates in outdated environments
We will now demand minimum versions of Python, pip and setuptools to be
present before we enable updating through the plugin.

Current minimum versions are those shipped with stock OctoPi 0.14.0.
2018-07-28 23:21:47 +02:00
Gina Häußge efe552264c SWU: Fix update button being visible if update impossible 2018-07-28 23:00:07 +02:00
Gina Häußge b7e788ec1b Work around an issue with sarge 0.1.5
Closes #2747
2018-07-25 17:34:54 +02:00
Gina Häußge e964d2410c Merge branch 'staging/maintenance' into maintenance
# Conflicts:
#	docs/bundledplugins/cura.rst
2018-07-25 16:56:43 +02:00
Gina Häußge 09284cd9b9 Merge branch 'rc/maintenance' into staging/maintenance 2018-07-25 16:54:21 +02:00
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 4963a4b849 docs: warning re expensive code in gcode hooks 2018-07-24 17:44:59 +02:00
Gina Häußge 46e425de88 Gcodeviewer: fix some JS warnings 2018-07-24 16:30:03 +02:00
Gina Häußge 376d38e0cf Gcodeviewer: remove printed/visited layer counts
Apparently it was confusing people and it's not really adding any kind
of meaningful information anyhow.
2018-07-24 16:28:41 +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 2e8f543aa3 Merge branch 'pr/2748' into maintenance 2018-07-23 09:45:24 +02:00
Iván d2dfd22a2c Remove malicious link as noticed in #2746 2018-07-22 02:49:32 +02:00
Gina Häußge b51cb31b46 Merge branch 'staging/maintenance' into maintenance 2018-07-20 12:26:16 +02:00
Gina Häußge eea1050a18 staging/maintenance is now 1.3.9rc5.dev 2018-07-20 12:26:00 +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 a37165d7d9 Tracking: Fix unit tests 2018-07-19 18:25:16 +02:00
Gina Häußge b06f804e9e Tracking: Change printer connection event 2018-07-19 18:17:29 +02:00
Gina Häußge d64ca79f05 Tracking: Only send requests if online 2018-07-19 18:17:29 +02:00
Gina Häußge 490ade5e17 Tracking: Granular control over tracked events 2018-07-19 18:17:28 +02:00
Gina Häußge 573503e84d Tracking: Track firmware name 2018-07-19 18:17:28 +02:00
Gina Häußge 9e0e4bf7b6 Pi Support: Allow configuration of vcgencmd 2018-07-19 18:17:28 +02:00
Gina Häußge 452645d950 Merge pull request #2742 from eyal0/faster_analysis3
Faster gcode analysis: Remove kwargs Vector.__init__ and simplify getCodeFloat
2018-07-19 09:41:06 +02:00
Eyal Soha d2bb731bd7 Remove kwargs from Vector constructor and also simplify getCodeFloat 2018-07-19 09:43:48 +03: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 40b5c272c4 Merge pull request #2723 from eyal0/always_gcode_analyze
Always run the GCodeAnalyser, even if the slicer provided analysis
2018-07-18 16:48:14 +02:00
Gina Häußge 31e4df44f9 Merge pull request #2739 from eyal0/faster_analysis2
Use infinity instead of None in MinMax3D to improve performance
2018-07-18 16:28:25 +02:00
Eyal Soha cd3c8ebbe6 Use infinity instead of None in MinMax3D to improve performance
Speed is improved by about 5%
2018-07-18 16:57:42 +03: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 59a435a787 Pi support: spelling fixes 2018-07-17 18:37:24 +02:00
Gina Häußge 71cc312ccc Pi support: move itertools import into debugging cluster 2018-07-17 18:25:13 +02:00
Gina Häußge 8d1ae438e5 Pi support: re-enable production config m) 2018-07-17 17:52:37 +02:00
Gina Häußge 7ebcb47955 Pi support: remove obsolete URL from about dialog 2018-07-17 17:49:16 +02:00
Gina Häußge 71e60183c5 Pi Support: add setting for throttle check
Just in case something acts up with that...
2018-07-17 17:49:03 +02:00
Gina Häußge 9c055137eb Pi Support: fix ordering of about dialog 2018-07-17 17:46:50 +02:00
Gina Häußge eaa8933782 Pi Support: fix state update push 2018-07-17 17:46:36 +02:00
Gina Häußge 0d330e3c5a Pi Support: slight change in timer startup 2018-07-17 16:59:03 +02:00
Gina Häußge 18ed113122 Pi Support: fix logic error 2018-07-17 16:57:04 +02:00
Gina Häußge 48e454856c Pi Support: change check implementation 2018-07-17 15:54:18 +02:00
Gina Häußge 917b86655f Tracking: always use percentage encoding
Otherwise we'll run into https://discuss.elastic.co/t/cant-parse-field/26557/4
on our tracking server
2018-07-17 15:53:41 +02:00
Gina Häußge 7a2225b332 Pi Support: strip 0 bytes from strings 2018-07-17 15:30:28 +02:00
Gina Häußge 20237a73ac Pi Support: Add debug logging to throttle check 2018-07-17 15:17:36 +02:00
Gina Häußge 4a3f894064 Tracking: fix a missed renamed field 2018-07-17 15:15:35 +02:00
Gina Häußge 0c9098f7bf Tracking: Fix a typo 2018-07-17 15:10:04 +02:00
Gina Häußge 53a2e04501 Tracking: adapt to new pi support plugin 2018-07-17 14:59:10 +02:00
Gina Häußge c6f5f1a0f7 Less scary message if a plugin doesn't pass check 2018-07-17 14:38:28 +02:00
Gina Häußge 1cff2581db OctoPi support => Pi support
* changed model detection implementation to use device-tree
  * now active if running on a Pi, regardless whether that runs OctoPi
    or not
  * detect undervoltage/overheat issues via vcgencmd and report back on
    UI
2018-07-17 14:38:12 +02:00
Gina Häußge 5cf02ac9ee Merge branch 'staging/maintenance' into maintenance 2018-07-16 15:21:49 +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 9559f09ec7 Merge pull request #2730 from eyal0/faster_analysis
Improve octoprint gcode analysis speed
2018-07-13 19:25:54 +02:00
Eyal Soha 542edbc3e6 Revert "Use infinity instead of None for faster MinMax3d"
This reverts commit 792fe328ef.

Most of the speed-up comes from removing the unneeded import and the unrolling so no big deal.
2018-07-13 20:07:35 +03:00
Gina Häußge f82d50b0f6 Some compatibility fixes 2018-07-13 18:41:50 +02:00
Gina Häußge e224b0ac71 Fix & extend unit tests 2018-07-13 18:02:42 +02:00
Gina Häußge 68f4ecefb0 Add hook to extend supported timelapse extensions
Implements #2729
2018-07-13 17:42:34 +02:00
Gina Häußge d73d930e5f Move to sarge 0.1.5
Replace async with async_ where necessary
2018-07-13 15:20:12 +02:00
Eyal 8c1262dd3f Replace infinity tests with inequality 2018-07-13 11:57:52 +03:00
Eyal Soha 792fe328ef Use infinity instead of None for faster MinMax3d 2018-07-13 00:44:04 +03:00
Eyal Soha 111a37e97e Unroll record for improved speed 2018-07-13 00:42:33 +03:00
Eyal Soha c2bb234c20 Remove extra import math 2018-07-13 00:29:43 +03: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
Eyal Soha 2dda3a0e32 Always run the GCodeAnalyser, even if the slicer provided analysis
The analysis from the Slicer or other sources is sent to the GCodeAnalyser, which can use it or ignore it.

This fixes https://github.com/foosel/OctoPrint/issues/2445#issuecomment-403599347
This fixes https://github.com/eyal0/OctoPrint-PrintTimeGenius/issues/13
2018-07-10 09:06:15 +03:00
Gina Häußge e2394446b0 Merge branch 'pr/2717' into maintenance 2018-07-06 17:15:45 +02:00
Gina Häußge 1befd0ecc1 Merge branch 'staging/maintenance' into maintenance 2018-07-06 16:59:48 +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 7587f34c94 Tracking: track software updates 2018-07-06 16:19:32 +02:00
Gina Häußge 6b54a15ed9 Tracking: add shutdown & extend startup data 2018-07-06 16:16:09 +02:00
Gina Häußge d391f0c12b Tracking: better kwarg encoding 2018-07-06 15:44:29 +02:00
Gina Häußge 8460a4173d Tracking: fix print reporting 2018-07-06 15:43:42 +02:00
Brad Fisher fe7149c715 Rendering speed enhancements; New event hooks 'onDragStart', 'onDrag', 'onDragStop', 'onViewportChange'; Bugfix to correct refresh() and refresh(0) both causing redraw of last drawn layer instead of refresh(0) drawing layer 0 2018-07-06 08:16:50 -05:00
Gina Häußge 443647e78e Add detection for Pi3B+ 2018-07-06 15:11:45 +02:00
Gina Häußge 50bb0bcfd4 Merge branch 'staging/maintenance' into maintenance 2018-07-06 14:35:54 +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 14661339ef Merge branch 'improve/tracking' into maintenance 2018-07-04 15:14:59 +02:00
Gina Häußge 8ca188e509 Tracking: rename tab in settings 2018-07-04 15:10:48 +02:00
Gina Häußge 3da4877d50 Tracking: Display instance ID in settings 2018-07-04 15:08:09 +02:00
Gina Häußge 382f10557e Tracking: Add explanation text & links 2018-07-04 11:17:17 +02:00
Gina Häußge d9c6cca370 Anonymous usage tracking 2018-07-03 19:06:53 +02:00
Gina Häußge abf4f90f0e Fix an issue with collision free sd name detection 2018-06-26 17:32:58 +02:00
Gina Häußge 13ab34a5c8 Better API key check 2018-06-25 18:53:42 +02:00
Gina Häußge 2a67772f46 Different base icon & setting
(cherry picked from commit dc61b61)
2018-06-25 12:47:31 +02:00
tedder f69718b060 make favicon color match custom theme color
With multiple octopis, the theme/header color is really nice for quickly distinguishing them. But it doesn't help with an ocean of open tabs. This does- simply carry the theme color onto the favicon.

I could do this as a plugin and/or make it a configurable setting, but it's very small change that doesn't need that much overhead, and generally I have opinions about having a plethora of setting flags for nonfunctional things. Thanks to @jneilliii for [helping me through the viewmodels](https://discourse.octoprint.org/t/where-can-i-get-the-theme-color/2354/5).

(cherry picked from commit e1089de)
2018-06-25 12:47:31 +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 08c384ac68 Merge pull request #2697 from eyal0/patch-2
estimatedPrintTime is in seconds, not minutes
2018-06-25 11:07:41 +02:00
Gina Häußge 00354f4a1e Merge pull request #2696 from eyal0/patch-1
Fix comment in types.py to match the code
2018-06-25 11:06:34 +02:00
Eyal 1a9b6c01a6 estimatedPrintTime is in seconds, not minutes
The documentation says that the estimated print time should be given in minute.  But in practice, when I give it in minutes, the GUI shows an error factor of 60.  By supplying it in seconds, the correct value is shown.

So it should probably actually be "in seconds"
2018-06-24 15:45:29 +03:00
Eyal c4dc7d0f55 Fix comment in types.py to match the code
The comment says that the key should be `_analysis` but in the code it is `analysis`: https://github.com/foosel/OctoPrint/blob/master/src/octoprint/slicing/__init__.py#L312

This fixes the comment but leaves the code unchanged.
2018-06-24 15:04:38 +03:00
Gina Häußge 5a60af9d13 Improve SD print detection 2018-06-22 11:22:22 +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 cb8ce62ec4 maintenance is now 1.3.10.dev 2018-06-20 15:52:46 +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
Gina Häußge c55c568bbd Preparing release of 1.3.8 2018-04-13 16:22:44 +02:00
Gina Häußge 45d8c28883 Pin psutil to 5.4.3
Fixes #2577
2018-04-13 15:31:44 +02:00
Gina Häußge 8076e59861 Add hotfix branch type & set to tag tracking 2018-04-13 15:31:01 +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
267 changed files with 20945 additions and 7766 deletions

No files matched your search

+1
View File
@@ -11,6 +11,7 @@ trim_trailing_whitespace = true
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/static/js/app/**.js]
indent_style = space
+135
View File
@@ -0,0 +1,135 @@
---
name: Bug report
about: Create a report to help improve OctoPrint
---
<!--
READ THE FOLLOWING FIRST:
If not already done, please read the the Contribution Guidelines that
are linked to the right under "Helpful resources" > "Contributing".
Also read the FAQ: https://faq.octoprint.org
This is a bug and feature tracker, please only use it to report bugs
or request features within OctoPrint (not OctoPi, not any OctoPrint
plugins and not unofficial OctoPrint versions).
Do not seek support here ("I need help with ...", "I have a
question ..."), that belongs on the community forum at
discourse.octoprint.org, NOT here.
Mark requests with a "[Request]" prefix in the title please. For bug
reports fully fill out the bug reporting template (if you don't know
where to find some information - it's all described in the Contribution
Guidelines linked up there in the big yellow box).
When reporting a bug do NOT delete ANY lines from the template.
Make sure any bug you want to report is still present with the CURRENT
OctoPrint version and that it does not vanish when you start OctoPrint
in safe mode - how to do that is also explained in the Contribution
Guidelines linked up there in the big yellow box.
Thank you!
-->
#### What were you doing?
<!--
Please be as specific as possible here. The maintainers will need to
reproduce your issue in order to fix it and that is not possible if they
don't know what you did to get it to happen in the first place.
Ideally provide exact steps to follow in order to reproduce your problem:
-->
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
<!--
If you encountered a problem with specific files of any sorts, make sure
to also include a link to a file with which to reproduce the problem.
-->
#### What did you expect to happen?
#### What happened instead?
#### Did the same happen when running OctoPrint in safe mode?
<!--
Test if you can reproduce your problem in safe mode. You can find information
on how to enable safe mode in the Contribution Guidelines.
If you can't reproduce in safe mode, this is a bug with one of your
installed third party plugins. Don't open a ticket here!
If you can't test this in safe mode, state why.
-->
#### Version of OctoPrint
<!--
Can be found in the lower left corner of the web interface. ALWAYS INCLUDE.
-->
#### Operating System running OctoPrint
<!--
OctoPi, Linux, Windows, MacOS, something else? With version please.
OctoPi's version can be found in /etc/octopi_version or in the lower left
corner of the web interface.
-->
#### Printer model & used firmware incl. version
<!--
If applicable, always include if unsure.
-->
#### Browser and version of browser, operating system running browser
<!--
If applicable, always include if unsure.
-->
#### Link to octoprint.log
<!--
On gist.github.com or pastebin.com. ALWAYS INCLUDE and never truncate.
The Contribution Guidelines tell you where to find that.
-->
#### Link to contents of terminal tab or serial.log
<!--
On gist.github.com or pastebin.com. If applicable, always include if unsure or
reporting communication issues. Never truncate.
serial.log is usually not written due to performance reasons and must be
enabled explicitly. Provide at the very least the FULL contents of your
terminal tab at the time of the bug occurrence, even if you do not have
a serial.log (which the Contribution Guidelines tell you where to find).
-->
#### Link to contents of Javascript console in the browser
<!--
On gist.github.com or pastebin.com or alternatively a screenshot. If applicable -
always include if unsure or reporting UI issues.
The Contribution Guidelines tell you where to find that.
-->
#### Screenshot(s)/video(s) showing the problem:
<!--
If applicable. Always include if unsure or reporting UI issues.
-->
I have read the FAQ.
+21
View File
@@ -0,0 +1,21 @@
---
name: Feature request
about: Suggest an idea for this project
---
<!--
Please make sure to add [Request] to your issue's title. Thank you!
-->
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
+8 -7
View File
@@ -11,22 +11,23 @@
master
meta/.*
rc/.*
hotfix/.*
prerelease
# neither should disconnected checkouts, e.g. 'git checkout <tag>'
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.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
fix/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 pep440-dev
improve/.* 1.3.10 fdf0f75ffa5731fee406c6e761e84a9d2b47aa43 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.10rc5
# so is regressionfix/...
staging/maintenance 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
regressionfix/.* 1.3.7rc4 9c5d996ea2b66a085392981a5e6e0ee341013674 pep440-dev
staging/maintenance 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b pep440-dev
regressionfix/.* 1.3.10rc5 e628aedbc11e2ef03ba4172b93e5be2a892b955b 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
+7
View File
@@ -87,6 +87,13 @@ 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)
* [Gaston Dombiak](https://github.com/gdombiak)
* [Brad Fisher](https://github.com/bradcfisher)
* [Aldo Hoeben](https://github.com/fieldofview)
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
+302 -1015
View File
File diff suppressed because it is too large. Load diff
+12 -8
View File
@@ -27,7 +27,7 @@ to **address problems in a timely manner** but also keep it possible for them
to **fix bugs, add new and improve on existing functionality** instead of doing
nothing but ticket management.
![Ticket flow chart](https://i.imgur.com/SmU7iCJ.png)
![Ticket flow chart](https://i.imgur.com/cw19qHX.png)
- **[Read the FAQ](https://faq.octoprint.org)**
- If you want to report a **bug**, [read "How to file a bug report" below](#how-to-file-a-bug-report)
@@ -39,11 +39,11 @@ nothing but ticket management.
[community forum at discourse.octoprint.org](https://discourse.octoprint.org) for
such support issues.
- If you are a **developer** that wants to brainstorm a pull request or possible
changes to the plugin system, add [Brainstorming] to your issue's title (e.g.
`[Brainstorming] New plugin hook for doing some cool stuff`).
changes to the plugin system, please get in touch on the
[community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/development).
- If you need **support**, have a **question** or some **other reason** that
doesn't fit any of the above categories, the issue tracker is not the right place.
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org) instead.
Consult the [community forum at discourse.octoprint.org](https://discourse.octoprint.org/c/support) instead.
No matter what kind of ticket you create, never mix two or more "ticket reasons"
into one ticket: One ticket per bug, request, brainstorming thread please.
@@ -53,7 +53,7 @@ into one ticket: One ticket per bug, request, brainstorming thread please.
> A bot is in place that monitors new tickets, automatically
> categorizes them and checks new bug reports for usage of the provided template.
> That bot will only bother you if you open a ticket that appears to be a bug (no
> `[Request]` or `[Brainstorming]` in the title) without the complete template, and it
> `[Request]` in the title) without the complete template, and it
> will do that only to ensure that all information needed to solve the issue is
> available for the maintainers to directly start tackling that problem.
@@ -301,7 +301,8 @@ the documentation.
the discussion going on how best to solve *this* in OctoPrint's plugin
system - maybe that's the actual PR you have been waiting for to contribute :)
2. If you plan to make **any large or otherwise disruptive changes to the
code or appearance, please open a "Brainstorming" ticket first** so
code or appearance, please get in touch on the
[forums](https://discourse.octoprint.org/c/development)** first so
that we can determine if it's a good time for your specific pull
request. It might be that we're currently in the process of making
heavy changes to the code locations you'd target as well, or your
@@ -311,7 +312,8 @@ the documentation.
3. Create your pull request **from a custom branch** on your end (e.g.
`dev/myNewFeature`)[1].
4. Create your pull request **only against the `maintenance` or `devel` branch**:
* if it's a bug fix for a bug in the current stable version: `maintenance` branch
* if it's a bug fix for a bug in the current stable version, an improvement of existing functionality or a
*small* new feature (e.g. a new hook, a new config flag, ...): `maintenance` branch
* otherwise: `devel` branch
5. Create **one pull request per feature/bug fix**.
6. Make sure there are **only relevant changes** included in your PR. No
@@ -472,7 +474,9 @@ the local version identifier to allow for an exact determination of the active c
* 2017-11-22: Added note on how to run the unit tests
* 2018-03-15: Link to new community forum and some clarifications re bug
reporting
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
* 2018-03-29: "Where to find version numbers" is now located on the FAQ
* 2018-10-18: Allow PRs against `maintenance` branch for improvements and small
new features, suggest getting in touch on the forum for larger changes
## Footnotes
* [1] - If you are wondering why, the problem is that anything that you add
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).
+16 -17
View File
@@ -1,58 +1,57 @@
# 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
* Andre Bubel
* Andrew Moorby
* Arnljot Arntsen
* Boris Hussein
* Brad Jackson
* Brian E. Tyler
* Christian Petropolis
* Christian Wolf
* COLLE+McVOY
* D Brian Kimmel
* DeltaMaker 3D Printers
* E3D BigBox
* Eric Betts
* Eric Slape
* Ernesto Martinez
* F. Kunsmann
* Frank Sander
* Gary Deen
* günter weber
* James Seigel
* Jeff Moe
* George Robles
* Jared Go
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* Josh Daniels
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kodama Inc.
* LA 3D Printer Repair
* Lewis Newby
* LulzBot®
* Makespace Madrid
* Mark Walker
* Martin Beattie
* Michael Aumock
* Miles Flavel
* mitchell hirsch
* Mohammed khorakiwala
* Noe Ruiz
* Mosaic Manufacturing
* Patrick McGinnis
* Peter Schmehl
* Prof Yuh Wen Chen
* Randy C. Will
* Robert Gusek
* Roger Strolz
* Roy Cortes
* 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 1446 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.
+97 -3
View File
@@ -12,8 +12,11 @@ Authorization
=============
OctoPrint's API expects an API key to be supplied with each request. This API key can be either the globally
configured one, a user specific one if "Access Control" is enabled or an :ref:`App Session Key <sec-api-apps-sessionkey>`.
Users are able to generate and revoke their custom API key via the "Change password" dialog.
configured one, a user specific one if "Access Control" is enabled or an app and user specific one as generated
by the authorization workflow implemented by the bundled :ref:`Application Keys Plugin <sec-bundledplugins-appkeys>` (since 1.3.10).
Clients are advised to implement the :ref:`Application Keys Plugin workflow <sec-bundledplugins-appkeys-workflow>` first and
fallback on directing the user to manually supply the the user specific API key. The global key should rarely be used.
The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
@@ -23,7 +26,7 @@ The API key must be supplied in the custom HTTP header ``X-Api-Key``, e.g.
Host: example.com
X-Api-Key: abcdef...
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`401`.
If it is missing or included but invalid, OctoPrint will directly return a response with status :http:statuscode:`403`.
For testing purposes it is also possible to supply the API key via a query parameter ``apikey``, e.g.
@@ -120,3 +123,94 @@ If CORS is not enabled you will get errors like the following::
XMLHttpRequest cannot load http://localhost:8081/api/files. No 'Access-Control-Allow-Origin'
header is present on the requested resource.
.. _sec-api-general-login:
Login
=====
.. http:post:: /api/login
Creates a login session or retrieves information about the currently existing session ("passive login").
Can be used in one of two ways: to login a user via username and password and create a persistent session (usually
from a UI in the browser), or to retrieve information about the active user (from an existing session or an API key)
via the ``passive`` flag.
Will return a :http:statuscode:`200` with a :ref:`login response <sec-api-general-datamodel-login>` on successful
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`401` in
case of a username/password mismatch or unknown user and a :http:statuscode:`403` in case of a deactivated account.
:json passive: If present, performs a passive login only, returning information about the current user that's
active either through an existing session or the used API key
:json user: (active login only) Username
:json pass: (active login only) Password
:json remember: (active login only) Whether to set a "remember me" cookie on the session
:status 200: Successful login
:status 401: Username/password mismatch or unknown user
:status 403: Deactivated account
.. _sec-api-general-logout:
Logout
======
.. http:post:: /api/logout
Ends the current login session of the current user.
Only makes sense in the context of browser based workflows.
Will return a :http:statuscode:`204`.
:status 204: No error
.. _sec-api-general-datamodel:
Data model
==========
.. _sec-api-general-datamodel-login:
Login response
--------------
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``name``
- 1
- string
- the user's name/id
* - ``active``
- 1
- boolean
- Whether the user's account is active or not
* - ``admin``
- 1
- boolean
- Whether the user has admin rights or not
* - ``user``
- 1
- boolean
- Whether the user has user rights or not (always ``true``)
* - ``apikey``
- 1
- string or None
- The user's API key, if set
* - ``settings``
- 1
- dict
- The user's settings, if any
* - ``session``
- 1
- string
- The session key, can be used to authenticate with the ``auth`` message on the :ref:`push API <sec-api-push>`.
* - ``_is_external_client``
- 1
- boolean
- Whether the client that made the request got detected as external from the local network or not.
+50 -8
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
@@ -219,7 +219,7 @@ Issue a print head command
axes values are relative amounts) or to absolute position (provided axes values are coordinates)
* ``speed``: Optional. Speed at which to move. If not provided, minimum speed for all selected axes from printer
profile will be used. If provided but ``false``, no speed parameter will be appended to the command. Otherwise
interpreted as an integer signifying the speed in mm/s, to append to the command.
interpreted as an integer signifying the speed in mm/min, to append to the command.
home
Homes the print head in all of the given axes. Additional parameters are:
@@ -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.
@@ -342,11 +362,13 @@ Issue a tool command
Extrudes the given amount of filament from the currently selected tool. Additional parameters:
* ``amount``: The amount of filament to extrude in mm. May be negative to retract.
* ``speed``: Optional. Speed at which to extrude. If not provided, maximum speed for E axis from printer
profile will be used. Otherwise interpreted as an integer signifying the speed in mm/min, to append to the 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 +483,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 +503,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
+32 -14
View File
@@ -47,23 +47,41 @@ Clients must ignore any unknown messages.
The data model of the attached payloads is described further below.
OctoPrint's SockJS socket also accepts one command from the client to the server,
the ``throttle`` command. Usually, OctoPrint will push the general state update
in the ``current`` message twice per second. For some clients that might still
be too fast, so they can signal a different factor to OctoPrint utilizing the
``throttle`` message. OctoPrint expects a single integer here which represents
the multiplier for the base rate limit of one message every 500ms. A value of
1 hence will produce the default behaviour of getting every update. A value of
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
message every 1.5s and so on.
OctoPrint's SockJS socket also accepts two commands from the client to the server.
Example for a ``throttle`` client-server-message:
* ``auth`` (since 1.3.10): With the ``auth`` message, clients may associate an
existing user session with the socket. That is of special importance to receive
any kind of messages if the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` is enabled
(as it is by default), since it will prevent any kind of status messages to be sent to connected unauthenticated
clients.
.. sourcecode:: javascript
The ``auth`` message expects the user id of the user to authenticate followed by ``:`` and a session key to be
obtained from the successful payload of a :ref:`(passive or active) login via the API <sec-api-general-login>`.
{
"throttle": 2
}
Example for a ``auth`` client-server-message:
.. sourcecode:: javascript
{
"auth": "someuser:LGZ0trf8By"
}
* ``throttle``: Usually, OctoPrint will push the general state update
in the ``current`` message twice per second. For some clients that might still
be too fast, so they can signal a different factor to OctoPrint utilizing the
``throttle`` message. OctoPrint expects a single integer here which represents
the multiplier for the base rate limit of one message every 500ms. A value of
1 hence will produce the default behaviour of getting every update. A value of
2 will set the rate limit to maximally one message every 1s, 3 to maximally one
message every 1.5s and so on.
Example for a ``throttle`` client-server-message:
.. sourcecode:: javascript
{
"throttle": 2
}
.. _sec-api-push-datamodel:
+262 -2
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``
-
@@ -136,7 +396,7 @@ mapped from the same fields in ``config.yaml`` unless otherwise noted:
-
* - ``feature.sdSupport``
-
* - ``feature.sdReleativePath``
* - ``feature.sdRelativePath``
-
* - ``feature.sdAlwaysAvailable``
-
+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``.
+67
View File
@@ -0,0 +1,67 @@
.. _sec-bundledplugins-announcements:
Announcement Plugin
===================
The OctoPrint Announcement Plugin comes bundled with OctoPrint (starting with 1.2.11).
It displays announcements fetched from OctoPrint's websites, such as important updates, release announcements, new
plugins and similar. Through some manual configuration via ``config.yaml`` it also allows adding additional channels
via RSS or Atom feed URLs.
.. _fig-bundledplugins-announcements-example1:
.. figure:: ../images/bundledplugins-announcements-example1.png
:align: center
:alt: Example notification
An example notification from the Announcement Plugin.
.. _fig-bundledplugins-announcements-example2:
.. figure:: ../images/bundledplugins-announcements-example2.png
:align: center
:alt: Announcement reader
The Announcement Plugin's reader dialog.
.. _fig-bundledplugins-announcements-settings:
.. figure:: ../images/bundledplugins-announcements-settings.png
:align: center
:alt: Announcement settings
The Announcement Plugin's settings dialog.
.. _sec-bundledplugins-announcements-configuration:
Configuring the plugin
----------------------
The plugin allows enabling and disabling the preconfigured announcement channels via its settings dialog.
On top of that it's possible to add additional announcement channels (as RSS or Atom feed URLs) or change the
configuration of the existing channels through ``config.yaml``.
The available configuration keys are:
* ``channels``: Configured announcement channels. A mapping from a unique identifier to a configuration structure
that follows this format:
* ``name``: Name of the channel, used e.g. in the title of the displayed notifications.
* ``description``: Description of the channel.
* ``priority``: ``1`` for high priority announcements (red notification), ``2`` for regular ones (yellow notification).
* ``type``: Currently unused.
* ``url``: URL for the feed acting as notification source, must be RSS or Atom format.
* ``enabled_channels``: List of identifiers of enabled channels.
* ``forced_channels``: List of identifiers of channels that cannot be disabled (currently only ``_important`` which is used sparingly).
* ``channel_order``: List of channel identifiers in the order they should appear in the UI.
* ``ttl``: Time to live of the channel cache in minutes (default: 6 hours).
* ``display_limit``: Limit of items to display per channel (default: 3).
* ``summary_limit``: Limit of characters to display from each channel entry (default: 300).
.. _sec-bundledplugins-announcements-sourcecode:
Source code
-----------
The source of the Announcement plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/announcements``.
+543
View File
@@ -0,0 +1,543 @@
.. _sec-bundledplugins-appkeys:
Application Keys Plugin
=======================
The OctoPrint Application Keys Plugin comes bundled with OctoPrint (starting with version 1.3.10).
It implements a workflow for third party apps or clients to obtain an application specific API key from OctoPrint to interact with it
on a user's behalf, via confirmation of the user through OctoPrint's web interface. Existing keys can be managed
on a per-user base as well as globally by administrators.
.. _fig-bundledplugins-appkeys-confirmation:
.. figure:: ../images/bundledplugins-appkeys-confirmation_prompt.png
:align: center
:alt: Confirmation
The plugin's confirmation generated for a new application key request.
.. _fig-bundledplugins-appkeys-user_settings:
.. figure:: ../images/bundledplugins-appkeys-user_settings.png
:align: center
:alt: Key management via user settings
Users can manage the application specific API keys registered to their account via their user settings.
.. _fig-bundledplugins-appkeys-settings:
.. figure:: ../images/bundledplugins-appkeys-settings.png
:align: center
:alt: Global key management via settings
Administrators can manage all application specific API keys registered to any user.
.. _sec-bundledplugins-appkeys-workflow:
Workflow
--------
The workflow to receive an API key for a third party client/an app via the Application Keys Plugin should consist
of the following steps:
1. The User opens the App and gets prompted to enter or select an instance URL. Optionally (recommended!) the User also
enters their username which is also their user ID into the App.
2. The App :ref:`probes for workflow support <sec-bundledplugins-appkeys-api-probe>` on the Server. If this request
doesn't get an HTTP :http:statuscode:`204` the App needs to direct the user to an alternative manual workflow
(copy-paste API key) and abort this one. Otherwise it proceeds to the next step.
3. The App sends a :ref:`key request <sec-bundledplugins-appkey-datamodel-keyrequest>` to the Server to start the
authorization process.
4. The Server triggers a confirmation dialog for the User on the Webinterface and returns an endpoint to the
App to poll for a decision in the ``Location`` header of an HTTP :http:statuscode:`201`.
5. The App uses the obtained request specific endpoint to poll for a decision every second. An HTTP :http:statuscode:`202`
signals that no decision has been made yet.
6. The User either accepts or denies the access request which makes the Webinterface send a
:ref:`decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` to the Server.
7. If the User accepted the request, the App receives an HTTP :http:statuscode:`200` with an attached
:ref:`API key response <sec-bundledplugins-appkey-datamodel-keyresponse>`. If they deny it, the App will receive
an HTTP :http:statuscode:`404`.
.. mermaid::
sequenceDiagram
participant User
participant App
participant Webinterface
participant Server
note over User, Server: Step 1, 2 & 3
User->>App: enters URL of instance to connect to and optional user_id
App->>Server: GET /plugin/appkeys/probe
alt Workflow unsupported
Server->>App: 404
App->>User: alternative workflow, copy-paste key manually
else Workflow supported
App->>Server: POST /plugin/appkeys/request, (app_name, user_id)
note over User, Server: Step 4
Server-->>Webinterface: plugin message for "appkeys" w/ (app_name, user_token, user_id)
Webinterface-->>User: Display confirmation dialog
Server->>App: 201, Location: /plugin/appkeys/request/<app_token>
note over User, Server: Step 5
loop Poll for decision
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 202
end
note over User, Server: Step 6 & 7
alt User accepts
User-->>Webinterface: Allow access
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (True)
Server->>Webinterface: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 200, api_key
else User denies
User-->>Webinterface: Deny access
Webinterface->>Server: POST /plugin/appkeys/decision/<user_token>, (False)
Server->>Webinterface: 204
App->>Server: GET /plugin/appkeys/request/<app_token>
Server->>App: 404
end
end
.. _sec-bundledplugins-appkeys-api:
API
---
.. _sec-bundledplugins-appkeys-api-probe:
Probe for workflow support
..........................
.. http:get:: /plugin/appkeys/probe
Probes for support of the workflow.
Normally returns an HTTP :http:statuscode:`204`, indicating workflow availability. If a different status code is returned
(usually an HTTP :http:statuscode:`404`), the plugin is disabled or not installed. Fall back to manual api key exchange.
:status 204: the workflow is supported
.. _sec-bundledplugins-appkeys-api-startauthprocess:
Start authorization process
...........................
.. http:post:: /plugin/appkeys/request
Starts the authorization process.
Expects a :ref:`Key request <sec-bundledplugins-appkey-datamodel-keyrequest>` as request body.
The ``app`` parameter should be a human readable identifier to use
for the application requesting access. It will be displayed to the user. Internally it will be used case insensitively,
so ``My App`` and ``my APP`` are considered the same application identifiers.
The optional ``user`` parameter should be used to limit the authorization process to a specified user. If the parameter
is left unset, any user will be able to complete the authorization process and grant access to the app with their
account. E.g. if a user ``me`` starts the process in an app, the app should request that name from the user and use
it in the ``user`` parameter. OctoPrint will then only display the authorization request on browsers the user ``me``
is logged in on.
:json app: application identifier to use for the request, case insensitive
:json user: optional user id to restrict the decision to the specified user
:status 201: authorization process started, polling URL to query can be found in ``Location`` header
.. _sec-bundledplugins-appkeys-api-polldecision:
Poll for decision on existing request
.....................................
.. http:get:: /plugin/appkeys/request/<str:app_token>
Endpoint generated per authorization request to poll for the result.
Returns an HTTP :http:statuscode:`202` while no decision has been made yet, an HTTP :http:statuscode:`200` and
a :ref:`Key response <sec-bundledplugins-appkey-datamodel-keyresponse>` if access has been granted and an
HTTP :http:statuscode:`404` if the request has been denied or timed out.
.. note::
The request will be considered stale and deleted internally if the polling endpoint for it isn't called
for more than 5s.
:status 200: access granted, API key in response body
:status 202: no decision has been made yet, continue polling
:status 404: access denied or request timed out
.. _sec-bundledplugins-appkeys-api-decide:
Decide on existing request
..........................
.. http:post:: /plugin/appkeys/decision/<str:user_token>
Endpoint to decide on the authorization request.
Expects a :ref:`Decision request <sec-bundledplugins-appkey-datamodel-decisionrequest>` as request body.
Returns an HTTP :http:statuscode:`204` on success.
:json decision: boolean value to indicate whether to confirm (``True``) or deny (``False``) access
:status 204: success
.. _sec-bundledplugins-appkeys-api-fetchlist:
Fetch list of existing application keys
.......................................
.. http:get:: /api/plugin/appkeys
Fetches a list of existing application keys and pending requests registered in the system for the current user.
If the additional optional parameter ``all`` is provided and the user has administrator rights, fetches a list
of *all** application keys and pending requests registered in the system for any user.
Returns a :http:statuscode:`200` with a :ref:`List response <sec-bundledplugins-appkey-datamodel-listreponse>` in the
body upon success.
:query all: Fetch all application keys and pending requests from all users. Requires administrator rights.
.. _sec-bundledplugins-appkeys-api-issuecommand:
Issue an application key command
................................
.. http:post:: /api/plugin/appkeys
Application key commands allow revoking existing application keys and manually generating new ones. The available
commands are:
revoke
Revokes an existing application key. Must belong to the user issuing the command, unless the user has admin rights
in which case they make revoke any application key in the system. Expects the key in question as parameter ``key``.
generate
Generates a new application key for the user, using the application identifier provided as parameter ``app``.
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
Requires user rights.
**Example revoke request**
Revokes the (fictional) key ``aabbccddeeff112233445566``.
.. sourcecode:: http
POST /api/plugin/appkeys HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "revoke",
"key": "aabbccddeeff112233445566"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
**Example generate request**
Generates a new key for application identifier "My awesome application 1.0".
.. sourcecode:: http
POST /api/plugin/appkeys HTTP/1.1
Host: example.com
Content-Type: application/json
X-Api-Key: abcdef...
{
"command": "generate",
"key": "My awesome application 1.0"
}
.. sourcecode:: http
HTTP/1.1 204 No Content
:json string command: The command to issue, either ``revoke`` or ``generate``
:json string key: ``revoke`` command: The key to revoke
:json string app: ``generate`` command: Application identifier for which to generate a key
:statuscode 204: No error
:statuscode 400: Invalid or missing parameter
.. _sec-bundledplugins-appkey-datamodel:
Data model
----------
.. _sec-bundledplugins-appkey-datamodel-keyrequest:
Key request
...........
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``app``
- 1
- str
- Application identifier to use for the request
* - ``user``
- 0..1
- str
- User identifier/name to restrict the request to
.. _sec-bundledplugins-appkey-datamodel-keyresponse:
Key response
............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``apikey``
- 1
- str
- the API key generated for the application
.. _sec-bundledplugins-appkey-datamodel-decisionrequest:
Decision request
................
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``decision``
- 1
- boolean
- ``True`` if the access request it to be granted, ``False`` otherwise
.. _sec-bundledplugins-appkey-datamodel-listreponse:
List response
.............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``keys``
- 1
- list of :ref:`key list entries <sec-bundledplugins-appkey-datamodel-keylistentry>`
- Keys registered in the system
* - ``pending``
- 1
- list of :ref:`pending list entries <sec-bundledplugins-appkey-datamodel-pendinglistentry>`
- Currently pending authorization requests
.. _sec-bundledplugins-appkey-datamodel-keylistentry:
Key list entry
..............
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``api_key``
- 1
- str
- API key
* - ``app_id``
- 1
- str
- Application identifier
* - ``user_id``
- 1
- str
- User ID of the key's owner
.. _sec-bundledplugins-appkey-datamodel-pendinglistentry:
Pending list entry
..................
.. list-table::
:widths: 15 5 10 30
:header-rows: 1
* - Name
- Multiplicity
- Type
- Description
* - ``app_id``
- 1
- str
- Application identifier
* - ``user_id``
- 0..1
- str
- optional: User ID of user who can grant or deny request
* - ``user_token``
- 1
- str
- Token to grant or deny request
.. _sec-bundledplugins-appkeys-jsclientlib:
JavaScript Client Library
-------------------------
.. js:function:: OctoPrintClient.plugins.appkeys.getKeys(opts)
Retrieves registered keys and pending requests for the current user.
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.getAllKeys(opts)
Retrieves registered keys and pending requests for all users.
Needs administrator rights.
See :ref:`Fetch list of existing application keys <sec-bundledplugins-appkeys-api-fetchlist>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.generateKey(app, opts)
Generates a key for the given ``app`` and the current user.
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
:param string app: Application identifier
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.revokeKey(key, opts)
Revokes the given ``key``. The key must belong to the current user, or the current user must have administrator
rights.
See :ref:`Issue an application key command <sec-bundledplugins-appkeys-api-issuecommand>` for details.
:param string key: Key to revoke
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.decide(token, decision, opts)
Decides on an existing authorization request.
See :ref:`Decide on existing request <sec-bundledplugins-appkeys-api-decide>` for more details.
:param string token: User token for which to make the decision, as pushed to the client via the socket.
:param boolean decision: Whether to grant access (``true``) or not (``false``).
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.probe(opts)
Probes for workflow support.
See :ref:`Probe for workflow support <sec-bundledplugins-appkeys-api-probe>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.request(app, opts)
Starts a new authorization request for the provided ``app`` identifier.
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.requestForUser(app, user, opts)
Starts a new authorization request for the provided ``app`` and ``user`` identifiers.
See :ref:`Start authorization process <sec-bundledplugins-appkeys-api-startauthprocess>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.checkDecision(token, opts)
Polls for a decision on an existing authorization request identified by ``token``.
See :ref:`Poll for decision on existing request <sec-bundledplugins-appkeys-api-polldecision>` for more details.
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. js:function:: OctoPrintClient.plugins.appkeys.authenticate(app, user, opts)
Convenience function that probes for support, issues a request and then automatically starts polling for a decision
on the returned polling endpoint every 1s, until either a positive or negative decision is returned. On success the
returned promise is resolved with the generated API key as argument. If anything goes wrong or there is no support
for the workflow, the promise is rejected.
**Example usage**
.. sourcecode:: javascript
OctoPrint.plugins.appkeys.authenticate("My App", "some_user")
.done(function(api_key) {
console.log("Got our API key:", api_key);
})
.fail(function() {
console.log("No API key for us");
})
:param string app: Application identifier
:param string user: Optional user identifier
:param object opts: Additional options for the request
:returns Promise: A `jQuery Promise <http://api.jquery.com/Types/#Promise>`_ for the request's response
.. _sec-bundledplugins-appkeys-sourcecode:
Source code
-----------
The source of the Application Keys plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/appkeys``.
+70
View File
@@ -0,0 +1,70 @@
.. _sec-bundledplugins-backup:
Backup Plugin
=============
The OctoPrint Backup Plugin comes bundled with OctoPrint (starting with 1.3.10).
It allows the creation and restoration of backups of OctoPrint's settings, data and installed plugins [#]_.
This allows easy migration
to newly setup instances as well as making regular backups to prevent data loss.
.. _fig-bundledplugins-backup-settings:
.. figure:: ../images/bundledplugins-backup-settings.png
:align: center
:alt: OctoPrint Backup Plugin
The plugin's settings panel with existing backups, the backup creation and restore sections.
As long as plugins adhere to the standard of storing their data and settings in OctoPrint's plugin data folders, their
data will be part of the backup. Note that the backups made by the Backup Plugin will *not* be part of any backups -
you'll need to persist the resulting zip files yourself!
.. _sec-bundledplugins-backup-cli:
Command line usage
------------------
The Backup Plugin implements a command line interface that allows creation and restoration of backups.
It adds two new commands, ``backup:backup`` and ``backup_restore``.
.. code-block:: none
$ octoprint plugins backup:backup --help
Initializing settings & plugin subsystem...
Usage: octoprint plugins backup:backup [OPTIONS]
Creates a new backup.
Options:
--exclude TEXT Identifiers of data folders to exclude, e.g. 'uploads' to
exclude uploads or 'timelapse' to exclude timelapses.
--help Show this message and exit.
$ octoprint plugins backup:restore --help
Initializing settings & plugin subsystem...
Usage: octoprint plugins backup:restore [OPTIONS] PATH
Restores an existing backup from the backup zip provided as argument.
OctoPrint does not need to run for this to proceed.
Options:
--help Show this message and exit.
.. note::
The ``backup:backup`` command can be useful in combination with a cronjob to create backups in regular intervals.
.. _sec-bundledplugins-backup-sourcecode:
Source code
-----------
The source of the Backup plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/backup``.
.. [#] Note that only those plugins that are available on `OctoPrint's official plugin repository <https://plugins.octoprint.org>`_
can be automatically restored. If you have plugins installed that are not available on there you'll get their
names and - if available - homepage URL displayed after restore in order to be able to manually reinstall them.
+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
+35
View File
@@ -0,0 +1,35 @@
.. _sec-bundledplugins-forcelogin:
ForceLogin Plugin
=================
The ForceLogin Plugin comes bundled with OctoPrint (starting with version 1.3.10). It removes the anonymous
read-only access that up until 1.3.10 was standard when accessing OctoPrint instances without being logged in and
instead forces users to log in if they want to get any kind of information from OctoPrint.
.. _fig-bundledplugins-forcelogin:
.. figure:: ../images/bundledplugins-forcelogin-dialog.png
:align: center
:alt: Forced login dialog
OctoPrint's new forced login dialog.
.. warning::
Keep in mind that **OctoPrint does not manage your webcam**, it merely embeds it. If you have a webcam,
it will still be accessible to users who are not logged in under its (guessable) URL. If you need to restrict
access to your webcam, you'll need to find a way to do so directly on the webcam server which - again -
is not OctoPrint itself.
.. note::
If you want back the old behaviour of allowing anonymous read-only access to your OctoPrint instance, disable
the ForceLogin Plugin in OctoPrint's plugin manager.
.. _sec-bundledplugins-forcelogin-sourcecode:
Source code
-----------
The source of the ForceLogin plugin is bundled with OctoPrint and can be found in
its source repository under ``src/octoprint/plugins/forcelogin``.
+5
View File
@@ -7,8 +7,13 @@ Bundled Plugins
.. toctree::
:maxdepth: 2
action_command_prompt.rst
announcements.rst
appkeys.rst
backup.rst
cura.rst
discovery.rst
forcelogin.rst
logging.rst
pluginmanager.rst
printer_safety_check.rst
+2 -7
View File
@@ -16,17 +16,12 @@ such identification.
An example of a warning generated by the Printer Safety Check
Currently the following firmwares produce this warning:
* Anet A8 stock firmware
Please refer to the `entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
for a list of currently identified printers.
If you know of further printers/printer firmwares that need to be added here, please
`get in touch on the forum and provide their response to an M115 <https://faq.octoprint.org/warning-firmware-unsafe>`_.
.. seealso::
`Entry on the "unsafe firmware" warning in OctoPrint's FAQ <https://faq.octoprint.org/warning-firmware-unsafe>`_
.. note::
Feel free to disable the plugin in OctoPrint's Plugin Manager if you feel like it is unnecessary. Be advised though
+50 -22
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,10 @@ Use the following settings to enable or disable OctoPrint features:
# Defaults to only M117.
autoUppercaseBlacklist:
- M117
- M118
# whether G90/G91 also influence absolute/relative mode of extruders
g90InfluencesExtruder: false
.. _sec-configuration-config_yaml-folder:
@@ -616,15 +620,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 +640,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 +899,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 +940,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 +974,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
@@ -1047,6 +1061,15 @@ Use the following settings to configure the server:
# How many days to leave unused entries in the preemptive cache config
until: 7
# Configuration of the client IP check to warn about connections from external networks
ipCheck:
# whether to enable the check, defaults to true
enabled: true
# additional non-local subnets to consider trusted, in CIDR notation, e.g. "192.168.1.0/24"
trustedSubnets: []
.. note::
@@ -1092,7 +1115,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
@@ -1149,7 +1177,7 @@ Use `Javascript regular expressions <https://developer.mozilla.org/en/docs/Web/J
# A list of filters to display in the terminal tab. Defaults to the filters shown below
terminalFilters:
- name: Suppress temperature messages
regex: '(Send: (N\d+\s+)?M105)|(Recv: ok T:)'
regex: '(Send: (N\d+\s+)?M105)|(Recv:\s+(ok\s+)?.*(B|T\d*):\d+)'
- name: Suppress SD status messages
regex: '(Send: (N\d+\s+)?M27)|(Recv: SD printing byte)'
- name: Suppress wait responses
+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.
+6 -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::
@@ -338,6 +338,8 @@ PrintFailed
* ``name``: the file's name
* ``path``: the file's path within its storage location
* ``origin``: the origin storage location of the file, either ``local`` or ``sdcard``
* ``time``: the elapsed time of the print when it failed, in seconds (float)
* ``reason``: the reason the print failed, either ``cancelled`` or ``error``
.. deprecated:: 1.3.0
+7 -1
View File
@@ -31,7 +31,13 @@ Internet!).
.. hint::
If you plan to have your OctoPrint instance accessible over the internet,
**always enable Access Control**.
**always enable Access Control** and ideally **don't make it accessible to
everyone over the internet but instead use a VPN** or at the very least
HTTP basic authentication on a layer above OctoPrint.
A physical device that includes heaters and stepper motors really should not be
publicly reachable by everyone with an internet connection, even with access
control enabled.
.. _sec-features-access_control-rerunning_wizard:
+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.
+5 -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``
@@ -157,9 +157,13 @@ The ``disable_hotends`` snippet is defined as follows:
.. code-block:: jinja
:caption: Default ``disable_hotends`` snippet
{% if printer_profile.extruder.sharedNozzle %}
M104 T0 S0
{% else %}
{% for tool in range(printer_profile.extruder.count) %}
M104 T{{ tool }} S0
{% endfor %}
{% endif %}
The ``disable_bed`` snippet is defined as follows:
Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.6 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
+7 -3
View File
@@ -80,9 +80,13 @@ connection options (``baseurl`` and ``apikey``) directly in the constructor or s
.. seealso::
`OctoPrint-ForceLogin <https://github.com/OctoPrint/OctoPrint-ForceLogin>`_
A plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI. Utilizes the
client library's :ref:`browser component <sec-jsclientlib-browser>` to login the user.
:ref:`Application Key Plugin <sec-bundledplugins-appkeys>`
A bundled plugin that implements an authorization workflow for third party clients. It adds various additional
methods to the JS Client Library.
:ref:`ForceLogin Plugin <sec-bundledplugins-forcelogin>`
A bundled plugin that disables anonymous access to the regular OctoPrint UI by implementing a custom UI and
various hooks. Utilizes the client library's :ref:`browser component <sec-jsclientlib-browser>` to login the
user.
.. toctree::
:maxdepth: 3
+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
+6
View File
@@ -6,4 +6,10 @@ octoprint.util
.. automodule:: octoprint.util
:members:
.. _sec-modules-util-commandline:
octoprint.util.commandline
--------------------------
.. automodule:: octoprint.util.commandline
:members:
+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)
+1 -1
View File
@@ -3,7 +3,7 @@
Helpers
=======
Helpers are methods that plugin can exposed to other plugins in order to make common functionality available on the
Helpers are methods that plugins can expose to other plugins in order to make common functionality available on the
system. They are registered with the OctoPrint plugin system through the use of the control property ``__plugin_helpers__``.
An example for providing some helper functions to the system can be found in the
+315 -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,66 @@ 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.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
: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.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
: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,11 +449,18 @@ 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.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Logs if the ``custom`` action (``// action:custom``) is received from the printer's firmware.
@@ -431,6 +498,13 @@ This describes actually two hooks:
trigger the *actual execution* of whatever functionality lies behind a given @ command, similar to
:ref:`the action command hook <sec-plugins-hook-comm-protocol-action>`.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within your handlers as
you will effectively block the send/receive loops, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
Pause the print on ``@wait`` (this mirrors the implementation of the built-in ``@pause`` command, just with a
@@ -577,6 +651,13 @@ This describes actually four hooks:
Note: Only one command of a given ``cmd_type`` (other than None) may be queued at a time. Trying to rewrite the ``cmd_type``
to one already in the queue will give an error.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the send loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
The following hook handler replaces all ``M107`` ("Fan Off", deprecated) with an ``M106 S0`` ("Fan On" with speed
@@ -612,6 +693,13 @@ octoprint.comm.protocol.gcode.received
empty string as the received line. Note that Python functions will also automatically return ``None`` if an empty
``return`` statement is used or just nothing is returned explicitly from the handler.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Looks for the response of an ``M115``, which contains information about the ``MACHINE_TYPE``, among other things.
@@ -641,6 +729,13 @@ octoprint.comm.protocol.gcode.error
Plugins might utilize this hook to handle errors generated by the printer that are recoverable in one way or
the other and should not trigger the normal handling that assumes the worst.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example:**
Looks for error messages containing "fan error" or "bed missing" (ignoring case) and marks them as handled by the
@@ -716,6 +811,13 @@ octoprint.comm.protocol.temperatures.received
additional sanity checking to be applied and invalid values to be filtered out. If a handler returns an empty
dictionary or ``None``, no further processing will take place.
.. warning::
Make sure to not perform any computationally expensive or otherwise long running actions within these handlers as
you will effectively block the receive loop, causing the communication with the printer to stall.
This includes I/O of any kind.
**Example**
The following example shows how to filter out actual temperatures that are outside a sane range of 1°C to 300°C.
@@ -801,6 +903,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 +1043,100 @@ 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-after_request:
octoprint.server.api.after_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: after_request_handlers_hook(*args, **kwargs)
Allows adding additional after-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-before_request:
octoprint.server.api.before_request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: after_request_handlers_hook(*args, **kwargs)
Allows adding additional before-request-handlers to API endpoints defined by OctoPrint itself and installed plugins.
Your plugin might need this to further restrict access to API methods. See the bundled "Force Login" plugin for a
usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-access_validator:
octoprint.server.http.access_validator
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: access_validator_hook(request, *args, **kwargs)
Allows adding additional access validators to the default tornado routers.
Your plugin might need to this to restrict acccess to downloads and webcam snapshots further. See the bundled
"Force Login" plugin for a usage example.
.. important::
Implementing this hook will make your plugin require a restart of OctoPrint for enabling/disabling it fully.
.. _sec-plugins-hook-server-http-bodysize:
octoprint.server.http.bodysize
@@ -1004,6 +1238,85 @@ octoprint.server.http.routes
:return: a list of 3-tuples with additional routes as defined above
:rtype: list
.. _sec-plugins-hook-server-sockjs-authed:
octoprint.server.sockjs.authed
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_authed_hook(socket, user, *args, **kwargs):
Allows plugins to be notified that a user got authenticated or deauthenticated on the socket (e.g. due to logout).
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user that got authenticated on the socket, or None if the user got deauthenticated
.. _sec-plugins-hook-server-sockjs-register:
octoprint.server.sockjs.register
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_registration_hook(socket, user, *args, **kwargs):
Allows plugins to prevent a new :ref:`push socket client <sec-api-push>` to be registered to the system.
Handlers should return either ``True`` or ``False``. ``True`` signals to proceed with normal registration. ``False``
signals to not register the client.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object which is about to be registered
:param object user: the user currently authenticated on the socket - might be None
:return: whether to proceed with registration (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-server-sockjs-emit:
octoprint.server.sockjs.emit
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: socket_emit_hook(socket, user, message, payload, *args, **kwargs):
Allows plugins to prevent any messages to be emitted on an existing :ref:`push connection <sec-api-push>`.
Handlers should return either ``True`` to allow the message to be emitted, or ``False`` to prevent it.
See the bundled :ref:`Forcelogin Plugin <sec-bundledplugins-forcelogin>` for an example on how to utilize this.
:param object socket: the socket object on which a message is about to be emitted
:param object user: the user currently authenticated on the socket - might be None
:param string message: the message type about to be emitted
:param dict payload: the payload of the message about to be emitted (may be None)
:return: whether to proceed with sending the message (``True``) or not (``False``)
:rtype: boolean
.. _sec-plugins-hook-timelapse-extensions:
octoprint.timelapse.extensions
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. py:function:: timelapse_extension_hook(*args, **kwargs)
Allows extending the set of supported file extensions for timelapse files. Handlers must return a list of
additional file extensions.
**Example**
Allow the management of timelapse GIFs with extension ``gif``.
.. code-block:: python
def get_timelapse_extensions(*args, **kwargs):
return ["gif"]
__plugin_hooks__ = {
"octoprint.timelapse.extensions": get_timelapse_extensions
}
:return: a list of additional file extensions
:rtype: list
.. _sec-plugins-hook-ui-web-templatetypes:
octoprint.ui.web.templatetypes
+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
+54 -47
View File
@@ -12,44 +12,46 @@ import octoprint_setuptools
#-----------------------------------------------------------------------------------------------------------------------
# Supported python versions
PYTHON_REQUIRES = ">=2.7.3,<3" # TODO change to >=2.7.9,<3 in 1.3.11
# 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
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"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.5post0",
"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.1,<6",
"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",
@@ -73,9 +75,6 @@ EXTRA_REQUIRES = dict(
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinx_rtd_theme",
# PyPi upload related
"pypandoc"
],
# Dependencies for developing OctoPrint plugins
@@ -84,15 +83,19 @@ EXTRA_REQUIRES = dict(
]
)
# Additional requirements for setup
SETUP_REQUIRES = []
# Dependency links for any of the aforementioned dependencies
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()
@@ -148,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"
python_requires = PYTHON_REQUIRES
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 = {
+63 -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"
@@ -561,6 +595,9 @@ def main():
# cut off stuff from the beginning
args = args[-1 * sys_args_length:] if sys_args_length else []
from octoprint.util.fixes import patch_sarge_async_on_py2
patch_sarge_async_on_py2()
from octoprint.cli import octo
octo(args=args, prog_name="octoprint", auto_envvar_prefix="OCTOPRINT")
+3
View File
@@ -71,3 +71,6 @@ def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle
click.echo("DONE:{}s".format(time.time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=" ", allow_unicode=True))
if __name__ == "__main__":
gcode_command()
+7 -3
View File
@@ -82,12 +82,16 @@ def run_server(basedir, configfile, host, port, debug, allow_root, logging_confi
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover)
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,
+6 -9
View File
@@ -256,7 +256,7 @@ class FileManager(object):
file_name = storage_manager.split_path(path)
# we'll use the default printer profile for the backlog since we don't know better
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default())
queue_entry = QueueEntry(file_name, entry, file_type, storage_type, path, self._printer_profile_manager.get_default(), None)
if self._analysis_queue.enqueue(queue_entry, high_priority=high_priority):
counter += 1
@@ -476,12 +476,9 @@ class FileManager(object):
path_in_storage = self._storage(destination).add_file(path, file_object, links=links, printer_profile=printer_profile, allow_overwrite=allow_overwrite, display=display)
if analysis is None:
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
else:
self._add_analysis_result(destination, path, analysis)
queue_entry = self._analysis_queue_entry(destination, path_in_storage, printer_profile=printer_profile, analysis=analysis)
if queue_entry:
self._analysis_queue.enqueue(queue_entry, high_priority=True)
_, name = self._storage(destination).split_path(path_in_storage)
eventManager().fire(Events.FILE_ADDED, dict(storage=destination,
@@ -700,7 +697,7 @@ class FileManager(object):
def _on_analysis_finished(self, entry, result):
self._add_analysis_result(entry.location, entry.path, result)
def _analysis_queue_entry(self, destination, path, printer_profile=None):
def _analysis_queue_entry(self, destination, path, printer_profile=None, analysis=None):
if printer_profile is None:
printer_profile = self._printer_profile_manager.get_current_or_default()
@@ -709,6 +706,6 @@ class FileManager(object):
file_type = get_file_type(absolute_path)
if file_type:
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile)
return QueueEntry(file_name, path, file_type[-1], destination, absolute_path, printer_profile, analysis)
else:
return None
+33 -9
View File
@@ -20,7 +20,7 @@ from octoprint.events import Events, eventManager
from octoprint.settings import settings
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile")):
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
@@ -33,6 +33,7 @@ class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, locatio
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
@@ -50,8 +51,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 +61,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)
@@ -299,7 +299,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in minutes
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
@@ -307,6 +307,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):
@@ -320,6 +342,8 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
import sys
import yaml
if self._current.analysis:
return self._current.analysis
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
@@ -343,7 +367,7 @@ class GcodeAnalysisQueue(AbstractAnalysisQueue):
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._aborted = False
p = sarge.run(command, async=True, stdout=sarge.Capture())
p = sarge.run(command, async_=True, stdout=sarge.Capture())
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
+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)
+9 -4
View File
@@ -21,6 +21,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import os
import logging
import threading
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
@@ -94,7 +95,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en
if plugin_restart_needing_hooks is None:
plugin_restart_needing_hooks = ["octoprint.server.http.*",
"octoprint.printer.factory"]
"octoprint.printer.factory",
"octoprint.timelapse.extensions"]
if plugin_obsolete_hooks is None:
plugin_obsolete_hooks = ["octoprint.comm.protocol.gcode"]
@@ -167,7 +169,8 @@ def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None):
return plugin_settings(plugin_key, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings)
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None, initialized=True):
def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None,
initialized=True):
"""
Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the
indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success
@@ -205,7 +208,6 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception.
initialized (boolean): Whether the plugin needs to be initialized (True) or not (False). Initialization status
is determined be presence of injected ``_identifier`` property.
"""
if not isinstance(types, (list, tuple)):
@@ -215,18 +217,21 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
if kwargs is None:
kwargs = dict()
logger = logging.getLogger(__name__)
plugins = plugin_manager().get_implementations(*types, sorting_context=sorting_context)
for plugin in plugins:
if initialized and not hasattr(plugin, "_identifier"):
continue
if hasattr(plugin, method):
logger.debug("Calling {} on {}".format(method, plugin._identifier))
try:
result = getattr(plugin, method)(*args, **kwargs)
if callback:
callback(plugin._identifier, plugin, result)
except Exception as exc:
logging.getLogger(__name__).exception("Error while calling plugin %s" % plugin._identifier)
logger.exception("Error while calling plugin %s" % plugin._identifier)
if error_callback:
error_callback(plugin._identifier, plugin, exc)
+77 -75
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):
@@ -843,7 +861,7 @@ class PluginManager(object):
if plugin.check():
return plugin
else:
self.logger.warn("Plugin \"{plugin}\" did not pass check".format(plugin=str(plugin)))
self.logger.info("Plugin {plugin} did not pass check, not loading.".format(plugin=str(plugin)))
return None
def _is_plugin_disabled(self, key):
@@ -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):
+21 -5
View File
@@ -25,9 +25,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
from .core import (Plugin, RestartNeedingPlugin, SortablePlugin)
# noinspection PyCompatibility
from past.builtins import basestring
class OctoPrintPlugin(Plugin):
"""
The parent class of all OctoPrint plugin mixins.
@@ -159,6 +156,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
is not actually up yet and none of your plugin's APIs or blueprints will be reachable yet. If you need to be
externally reachable, use :func:`on_after_startup` instead or additionally.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_startup``.
:param string host: the host the server will listen on, may be ``0.0.0.0``
@@ -171,6 +172,10 @@ class StartupPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called just after launch of the server, so when the listen loop is actually running already.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``StartupPlugin.on_after_startup``.
"""
@@ -191,6 +196,10 @@ class ShutdownPlugin(OctoPrintPlugin, SortablePlugin):
"""
Called upon the imminent shutdown of OctoPrint.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
The relevant sorting context is ``ShutdownPlugin.on_shutdown``.
"""
pass
@@ -225,6 +234,8 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
js
JavaScript files, such as additional view models
jsclient
JavaScript files containing additional parts for the JS Client Library (since 1.3.10)
css
CSS files with additional styles, will be embedded into delivered pages when not running in LESS mode.
less
@@ -239,6 +250,7 @@ class AssetPlugin(OctoPrintPlugin, RestartNeedingPlugin):
def get_assets(self):
return dict(
js=['js/my_file.js', 'js/my_other_file.js'],
clientjs=['clientjs/my_file.js'],
css=['css/my_styles.css'],
less=['less/my_styles.less']
)
@@ -1443,7 +1455,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!
"""
@@ -1799,6 +1811,10 @@ class EventHandlerPlugin(OctoPrintPlugin):
"""
Called by OctoPrint upon processing of a fired event on the platform.
.. warning::
Do not perform long-running or even blocking operations in your implementation or you **will** block and break the server.
Arguments:
event (str): The type of event that got fired, see :ref:`the list of events <sec-events-available_events>`
for possible values
@@ -1984,7 +2000,7 @@ class SlicerPlugin(OctoPrintPlugin):
For jobs that finished successfully, ``result`` should be a :class:`dict` containing additional information
about the slicing job under the following keys:
_analysis
analysis
Analysis result of the generated machine code as returned by the slicer itself. This should match the
data structure described for the analysis queue of the matching machine code format, e.g.
:class:`~octoprint.filemanager.analysis.GcodeAnalysisQueue` for GCODE files.
@@ -0,0 +1,167 @@
# 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"],
clientjs=["clientjs/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,25 @@
(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;
});
@@ -0,0 +1,78 @@
$(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>
@@ -372,15 +372,24 @@ class AnnouncementPlugin(octoprint.plugin.AssetPlugin,
result = []
if "entries" in feed:
for entry in feed["entries"]:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
try:
internal_entry = self._to_internal_entry(entry, read_until=read_until)
if internal_entry:
result.append(internal_entry)
except:
self._logger.exception("Error while converting entry from feed, skipping it")
return result
def _to_internal_entry(self, entry, read_until=None):
"""Convert feed entries to internal data structure."""
published = calendar.timegm(entry["published_parsed"])
timestamp = entry.get("published_parsed",
entry.get("updated_parsed",
None))
if timestamp is None:
return None
published = calendar.timegm(timestamp)
read = True
if read_until is not None:
@@ -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 -->
+403
View File
@@ -0,0 +1,403 @@
# coding=utf-8
from __future__ import absolute_import
import flask
import threading
import os
import yaml
import codecs
import time
from binascii import hexlify
from collections import defaultdict
from flask_babel import gettext
import octoprint.plugin
from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, no_firstrun_access
from octoprint.server import NO_CONTENT, current_user, admin_permission
from octoprint.util import atomic_write, monotonic_time, ResettableTimer
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
self.poll_timeout.start()
def external(self):
return dict(app_id=self.app_id,
user_id=self.user_id,
user_token=self.user_token)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return dict(app_id=self.app_id,
api_key=self.api_key,
user_id=self.user_id)
def internal(self):
return dict(app_id=self.app_id,
api_key=self.api_key)
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
##~~ TemplatePlugin
def get_template_configs(self):
return [dict(type="usersettings", name=gettext("Application Keys")),
dict(type="settings", name=gettext("Application Keys"))]
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/appkeys.js"],
clientjs=["clientjs/appkeys.js"],
less=["less/appkeys.less"],
css=["css/appkeys.css"])
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(self._identifier, dict(type="request_access",
app_name=app_name,
user_token=user_token,
user_id=user_id))
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return dict(generate=["app"],
revoke=["key"])
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and admin_permission.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=map(lambda x: x.external(), keys),
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
self._add_api_key(user_id, app_name.strip())
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
timeout_callback=self._expire_pending))
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(self._identifier, dict(
type="end_request",
user_token=user_token
))
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = filter(lambda x: x.created >= cutoff,
self._pending_decisions)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = filter(lambda x: x.user_token != user_token, self._pending_decisions)
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = filter(lambda x: x.app_token != app_token, self._ready_decisions)
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = filter(lambda x: x.api_key != api_key, data)
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if filter(lambda x: x.api_key == api_key, data):
return self._user_manager.findUser(userid=user_id)
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return hexlify(os.urandom(16))
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with codecs.open(self._key_path, "rb", encoding="utf-8", errors="strict") as f:
persisted = yaml.safe_load(f)
except:
self._logger.exception("Could not load application keys from {}".format(self._key_path))
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = dict()
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path) as f:
yaml.safe_dump(to_persist, f)
except:
self._logger.exception("Could not write application keys to {}".format(self._key_path))
__plugin_name__ = u"Application Keys Plugin"
__plugin_description__ = u"Implements a workflow for third party clients to obtain API keys"
__plugin_author__ = u"Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin third party clients will no longer be able to "
u"obtain an API key without you manually copy-pasting it.")
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key
}
@@ -0,0 +1,98 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintAppKeysClient = function(base) {
this.base = base;
};
OctoPrintAppKeysClient.prototype.getKeys = function(opts) {
return this.base.simpleApiGet("appkeys", opts);
};
OctoPrintAppKeysClient.prototype.getAllKeys = function(opts) {
return this.base.get(OctoPrintClient.prototype.getSimpleApiUrl("appkeys") + "?all=true", opts);
};
OctoPrintAppKeysClient.prototype.generateKey = function(app, opts) {
return this.base.simpleApiCommand("appkeys", "generate", {"app": app}, opts);
};
OctoPrintAppKeysClient.prototype.revokeKey = function(key, opts) {
return this.base.simpleApiCommand("appkeys", "revoke", {"key": key}, opts);
};
OctoPrintAppKeysClient.prototype.decide = function(token, decision, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "decision/" + token, {decision: !!decision}, opts);
};
OctoPrintAppKeysClient.prototype.probe = function(opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "probe", opts);
};
OctoPrintAppKeysClient.prototype.request = function(app, opts) {
return this.requestForUser(app, undefined, opts);
};
OctoPrintAppKeysClient.prototype.requestForUser = function(app, user, opts) {
return this.base.postJson(this.base.getBlueprintUrl("appkeys") + "request", {app: app, user: user}, opts);
};
OctoPrintAppKeysClient.prototype.checkDecision = function(token, opts) {
return this.base.get(this.base.getBlueprintUrl("appkeys") + "request/" + token, opts);
};
OctoPrintAppKeysClient.prototype.authenticate = function(app, user) {
var deferred = $.Deferred();
var client = this;
client.probe()
.done(function() {
client.requestForUser(app, user)
.done(function(response) {
var token = response.app_token;
if (!token) {
// no token received, something went wrong
deferred.reject();
return;
}
var interval = 1000;
var poll = function() {
client.checkDecision(token)
.done(function(response) {
if (response.api_key) {
// got a decision, resolve the promise
deferred.resolve(response.api_key);
} else {
// no decision yet, poll a bit more
deferred.notify();
window.setTimeout(poll, interval);
}
})
.fail(function() {
// something went wrong
deferred.reject();
});
};
window.setTimeout(poll, interval);
})
.fail(function() {
// something went wrong
deferred.reject();
});
})
.fail(function() {
// workflow unsupported
deferred.reject();
});
return deferred.promise();
};
OctoPrintClient.registerPluginComponent("appkeys", OctoPrintAppKeysClient);
return OctoPrintAppKeysClient;
});
@@ -0,0 +1 @@
#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions{width:75px;text-align:center}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_actions a,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_actions a{color:#000}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_user,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_user{width:100px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox,#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox{text-align:center;width:10px}#settings_plugin_appkeys_allkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox],#settings_plugin_appkeys_userkeys_table .settings_plugin_appkeys_checkbox input[type=checkbox]{margin-top:0}
@@ -0,0 +1,308 @@
$(function() {
function UserAppKeysViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.keys = new ItemListHelper(
"plugin.appkeys.userkeys",
{
"app": function (a, b) {
// sorts ascending
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
return 0;
}
},
{
},
"app",
[],
[],
5
);
self.pending = {};
self.openRequests = {};
self.editorApp = ko.observable();
self.requestData = function() {
OctoPrint.plugins.appkeys.getKeys()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.keys.updateItems(response.keys);
self.pending = response.pending;
_.each(self.pending, function(data, token) {
self.openRequests[token] = self.promptForAccess(data.app_id, token);
})
};
self.generateKey = function() {
return OctoPrint.plugins.appkeys.generateKey(self.editorApp())
.done(self.requestData)
.done(function() {
self.editorApp("");
});
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
perform);
};
self.allowApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, true)
.done(self.requestData);
};
self.denyApp = function(token) {
return OctoPrint.plugins.appkeys.decide(token, false)
.done(self.requestData);
};
self.promptForAccess = function(app, token) {
var message = gettext("\"<strong>%(app)s</strong>\" has requested access to control OctoPrint through the API.");
message = _.sprintf(message, {app: app});
message = "<p>" + message + "</p><p>" + gettext("Do you want to allow access to this application with your user account?") + "</p>";
return new PNotify({
title: gettext("Access Request"),
text: message,
hide: false,
icon: "fa fa-key",
confirm: {
confirm: true,
buttons: [{
text: gettext("Allow"),
click: function(notice) {
self.allowApp(token);
notice.remove();
}
}, {
text: gettext("Deny"),
click: function(notice) {
self.denyApp(token);
notice.remove();
}
}]
},
buttons: {
sticker: false,
closer: false
}
});
};
self.onUserSettingsShown = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "appkeys") {
return;
}
var app, token, user;
if (data.type === "request_access" && self.loginState.isUser()) {
app = data.app_name;
token = data.user_token;
user = data.user_id;
if (user && user !== self.loginState.username()) {
return;
}
if (self.pending[token] !== undefined) {
return;
}
self.openRequests[token] = self.promptForAccess(app, token);
} else if (data.type === "end_request") {
token = data.user_token;
if (self.openRequests[token] !== undefined) {
// another instance responded to the access request before the current user did
if (self.openRequests[token].state !== "closed") {
self.openRequests[token].remove();
}
delete self.openRequests[token]
}
}
};
}
function AllAppKeysViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.keys = new ItemListHelper(
"plugin.appkeys.allkeys",
{
"user_app": function (a, b) {
// sorts ascending, first by user, then by app
if (a["user_id"] > b["user_id"]) return 1;
if (a["user_id"] < b["user_id"]) return -1;
if (a["app_id"].toLowerCase() > b["app_id"].toLowerCase()) return 1;
if (a["app_id"].toLowerCase() < b["app_id"].toLowerCase()) return -1;
return 0;
}
},
{
},
"user_app",
[],
[],
10
);
self.users = ko.observableArray([]);
self.apps = ko.observableArray([]);
self.markedForDeletion = ko.observableArray([]);
self.onSettingsShown = function() {
self.requestData();
};
self.onUserLoggedIn = function() {
self.requestData();
};
self.requestData = function() {
OctoPrint.plugins.appkeys.getAllKeys()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.keys.updateItems(response.keys);
var users = [];
var apps = [];
_.each(response.keys, function(key) {
users.push(key.user_id);
apps.push(key.app_id.toLowerCase());
});
users = _.uniq(users);
users.sort();
self.users(users);
apps = _.uniq(apps);
apps.sort();
self.apps(apps);
};
self.revokeKey = function(key) {
var perform = function() {
OctoPrint.plugins.appkeys.revokeKey(key)
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
perform);
};
self.revokeMarked = function() {
var perform = function() {
self._bulkRevoke(self.markedForDeletion())
.done(function() {
self.markedForDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke %(count)d application keys."), {count: self.markedForDeletion().length}),
perform);
};
self.markAllOnPageForDeletion = function() {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(self.keys.paginatedItems(), "api_key"))));
};
self.markAllForDeletion = function() {
self.markedForDeletion(_.uniq(_.map(self.keys.allItems, "api_key")));
};
self.markAllByUserForDeletion = function(user) {
self.markAllByFilterForDeletion(function(e) { return (e.user_id === user); });
};
self.markAllByAppForDeletion = function(app) {
self.markAllByFilterForDeletion(function(e) { return (e.app_id.toLowerCase() === app); })
};
self.markAllByFilterForDeletion = function(filter) {
self.markedForDeletion(_.uniq(self.markedForDeletion().concat(_.map(_.filter(self.keys.allItems, filter), "api_key"))));
};
self.clearMarked = function() {
self.markedForDeletion.removeAll();
};
self._bulkRevoke = function(keys) {
var title, message, handler;
title = gettext("Revoking application keys");
message = _.sprintf(gettext("Revoking %(count)d application keys..."), {count: keys.length});
handler = function(key) {
return OctoPrint.plugins.appkeys.revokeKey(key)
.done(function() {
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: key});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: key, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: keys.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(keys, function(key) {
var request = handler(key);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push([
UserAppKeysViewModel,
["loginStateViewModel"],
["#usersettings_plugin_appkeys"]
]);
OCTOPRINT_VIEWMODELS.push([
AllAppKeysViewModel,
["loginStateViewModel"],
["#settings_plugin_appkeys"]
])
});
@@ -0,0 +1,24 @@
#settings_plugin_appkeys_userkeys_table,
#settings_plugin_appkeys_allkeys_table {
.settings_plugin_appkeys_app {
}
.settings_plugin_appkeys_actions {
width: 75px;
text-align: center;
a {
color: black;
}
}
.settings_plugin_appkeys_user {
width: 100px;
}
.settings_plugin_appkeys_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
}
@@ -0,0 +1,59 @@
<div data-bind="visible: keys.allSize() <= 0">
<p>{{ _('There are no application keys registered yet.') }}</p>
</div>
<div data-bind="visible: keys.allSize() > 0">
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markAllOnPageForDeletion">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllForDeletion">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li class="dropdown-submenu">
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by user...') }}</a>
<ul class="dropdown-menu" data-bind="foreach: users">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByUserForDeletion($data) }, text: $data"></a></li>
</ul>
</li>
<li class="dropdown-submenu">
<a href="javascript:void(0)" data-bind="javascript:void(0)">{{ _('Select all by app...') }}</a>
<ul class="dropdown-menu" data-bind="foreach: apps">
<li><a href="javascript:void(0)" data-bind="click: function() { $root.markAllByAppForDeletion($data) }, text: $data"></a></li>
</ul>
</li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarked">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: revokeMarked, enable: markedForDeletion().length > 0">{{ _('Revoke selected') }}</button>
</div>
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_allkeys_table">
<thead>
<tr>
<th class="settings_plugin_appkeys_checkbox"></th>
<th class="settings_plugin_appkeys_user">{{ _('User') }}</th>
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: keys.paginatedItems">
<tr>
<td class="settings_plugin_appkeys_checkbox"><input type="checkbox" data-bind="value: api_key, checked: $root.markedForDeletion"></td>
<td class="settings_plugin_appkeys_user"><span data-bind="text: user_id"></span></td>
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: keys.pages">
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
</ul>
</div>
</div>
@@ -0,0 +1,49 @@
<legend>{{ _('Registered application keys') }}</legend>
<div data-bind="visible: keys.allSize() <= 0">
<p>{{ _('There are no application keys registered yet.') }}</p>
</div>
<div data-bind="visible: keys.allSize() > 0">
<table class="table table-condensed table-hover" id="settings_plugin_appkeys_userkeys_table">
<thead>
<tr>
<th class="settings_plugin_appkeys_app">{{ _('Application identifier') }}</th>
<th class="settings_plugin_appkeys_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: keys.paginatedItems">
<tr>
<td class="settings_plugin_appkeys_app"><span data-bind="text: app_id"></span><br /><small class="muted">{{ _('API Key') }}: <span data-bind="text: api_key"></span> <a href="javascript:void(0)" title="{{ _('Copy API Key to clipboard') }}" data-bind="click: function() { copyToClipboard(api_key) }"><i class="fa fa-copy"></i></a></small></td>
<td class="settings_plugin_appkeys_actions"><a href="javascript:void(0)" title="{{ _('Revoke') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: keys.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: keys.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: keys.pages">
<li data-bind="css: { active: $data.number === $root.keys.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.keys.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: keys.currentPage() === keys.lastPage()}"><a href="javascript:void(0)" data-bind="click: keys.nextPage">»</a></li>
</ul>
</div>
</div>
<legend>{{ _('Manually generate an application key') }}</legend>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Application identifier') }}</label>
<div class="controls">
<input type="text" data-bind="value: editorApp">
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="click: generateKey">{{ _('Generate') }}</button>
</div>
</div>
</form>
+925
View File
@@ -0,0 +1,925 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from octoprint.settings import default_settings
from octoprint.plugin.core import FolderOrigin
from octoprint.server import admin_permission, NO_CONTENT
from octoprint.server.util.flask import restricted_access
from octoprint.util import is_hidden_path
from octoprint.util.version import get_octoprint_version_string, get_octoprint_version, get_comparable_version, is_octoprint_compatible
from octoprint.util.platform import is_os_compatible
from octoprint.util.pip import LocalPipCaller
try:
from os import scandir
except ImportError:
from scandir import scandir
try:
import zlib # check if zlib is available
except ImportError:
zlib = None
from flask_babel import gettext
import codecs
import flask
import logging
import os
import requests
import sarge
import shutil
import tempfile
import threading
import time
import zipfile
import json
import sys
import traceback
UNKNOWN_PLUGINS_FILE = "unknown_plugins_from_restore.json"
class BackupPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.StartupPlugin):
_pip_caller = None
# noinspection PyMissingConstructor
def __init__(self):
self._in_progress = []
self._in_progress_lock = threading.RLock()
##~~ StarupPlugin
def on_after_startup(self):
self._clean_dir_backup(self._settings._basedir,
on_log_progress=self._logger.info)
##~~ AssetPlugin
def get_assets(self):
return dict(js=["js/backup.js"],
clientjs=["clientjs/backup.js"],
css=["css/backup.css"],
less=["less/backup.less"])
##~~ BlueprintPlugin
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_state(self):
backups = self._get_backups()
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(backups=backups,
backup_in_progress=len(self._in_progress) > 0,
unknown_plugins=unknown_plugins,
restore_supported=is_os_compatible(["!windows"]))
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_unknown_plugins(self):
# TODO add caching
unknown_plugins = self._get_unknown_plugins()
return flask.jsonify(unknown_plugins=unknown_plugins)
@octoprint.plugin.BlueprintPlugin.route("/unknown_plugins", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
def delete_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
try:
os.remove(data_file)
except:
pass
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["GET"])
@admin_permission.require(403)
@restricted_access
def get_backups(self):
backups = self._get_backups()
return flask.jsonify(backups=backups)
@octoprint.plugin.BlueprintPlugin.route("/backup", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def create_backup(self):
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
data = flask.request.json
exclude = data.get("exclude", [])
def on_backup_start(name, temporary_path, exclude):
self._logger.info(u"Creating backup zip at {} (excluded: {})...".format(temporary_path,
u",".join(exclude) if len(exclude) else "-"))
with self._in_progress_lock:
self._in_progress.append(name)
self._send_client_message("backup_started", payload=dict(name=name))
def on_backup_done(name, final_path, exclude):
with self._in_progress_lock:
self._in_progress.remove(name)
self._send_client_message("backup_done", payload=dict(name=name))
self._logger.info(u"... done creating backup zip.")
def on_backup_error(name, exc_info):
with self._in_progress_lock:
try:
self._in_progress.remove(name)
except ValueError:
# we'll ignore that
pass
self._send_client_message("backup_error", payload=dict(name=name,
error=u"{}".format(exc_info[1])))
self._logger.error(u"Error while creating backup zip", exc_info=exc_info)
thread = threading.Thread(target=self._create_backup,
args=(backup_file,),
kwargs=dict(exclude=exclude,
settings=self._settings,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_backup_start=on_backup_start,
on_backup_done=on_backup_done,
on_backup_error=on_backup_error))
thread.daemon = True
thread.start()
response = flask.jsonify(started=True,
name=backup_file)
response.status_code = 201
return response
@octoprint.plugin.BlueprintPlugin.route("/backup/<filename>", methods=["DELETE"])
@admin_permission.require(403)
@restricted_access
def delete_backup(self, filename):
backup_folder = self.get_plugin_data_folder()
full_path = os.path.realpath(os.path.join(backup_folder, filename))
if full_path.startswith(backup_folder) \
and os.path.exists(full_path) \
and not is_hidden_path(full_path):
try:
os.remove(full_path)
except:
self._logger.exception(u"Could not delete {}".format(filename))
raise
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/restore", methods=["POST"])
@admin_permission.require(403)
@restricted_access
def perform_restore(self):
if not is_os_compatible(["!windows"]):
return flask.make_response(u"Invalid request, the restores are not supported on the underlying operating system", 400)
input_name = "file"
input_upload_path = input_name + "." + self._settings.global_get(["server", "uploads", "pathSuffix"])
if input_upload_path in flask.request.values:
# file to restore was uploaded
path = flask.request.values[input_upload_path]
elif flask.request.json and "path" in flask.request.json:
# existing backup is supposed to be restored
backup_folder = self.get_plugin_data_folder()
path = os.path.realpath(os.path.join(backup_folder, flask.request.json["path"]))
if not path.startswith(backup_folder) \
or not os.path.exists(path) \
or is_hidden_path(path):
return flask.abort(404)
else:
return flask.make_response(u"Invalid request, neither a file nor a path of a file to restore provided", 400)
def on_install_plugins(plugins):
force_user = self._settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
pip_args = self._settings.global_get(["plugins", "pluginmanager", "pip_args"])
def on_log(line):
self._logger.info(line)
self._send_client_message("logline", dict(line=line, type="stdout"))
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to this version "
u"of OctoPrint".format(plugin["id"]))
elif not os_compatible:
self._logger.warn(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
self._send_client_message("plugin_incompatible", dict(plugin=plugin["id"],
octoprint_compatible=octoprint_compatible,
os_compatible=os_compatible))
continue
self._logger.info(u"Installing plugin {}".format(plugin["id"]))
self._send_client_message("installing_plugin", dict(plugin=plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
pip_args=pip_args,
on_log=on_log)
def on_report_unknown_plugins(plugins):
self._send_client_message("unknown_plugins", payload=dict(plugins=plugins))
def on_log_progress(line):
self._logger.info(line)
self._send_client_message("logline", payload=dict(line=line, stream="stdout"))
def on_log_error(line, exc_info=None):
self._logger.error(line, exc_info=exc_info)
self._send_client_message("logline", payload=dict(line=line, stream="stderr"))
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
self._send_client_message("logline", payload=dict(line=line.rstrip(), stream="stderr"))
def on_restore_start(path):
self._send_client_message("restore_started")
def on_restore_done(path):
self._send_client_message("restore_done")
def on_restore_failed(path):
self._send_client_message("restore_failed")
def on_invalid_backup(line):
on_log_error(line)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
# noinspection PyTypeChecker
thread = threading.Thread(target=self._restore_backup,
args=(path,),
kwargs=dict(settings=self._settings,
plugin_manager=self._plugin_manager,
datafolder=self.get_plugin_data_folder(),
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_invalid_backup=on_invalid_backup,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_restore_start=on_restore_start,
on_restore_done=on_restore_done,
on_restore_failed=on_restore_failed))
thread.daemon = True
thread.start()
return flask.jsonify(started=True)
##~~ tornado hook
def route_hook(self, *args, **kwargs):
from octoprint.server.util.tornado import LargeResponseHandler, path_validation_factory
from octoprint.util import is_hidden_path
from octoprint.server import app
from octoprint.server.util.tornado import access_validation_factory
from octoprint.server.util.flask import admin_validator
return [
(r"/download/(.*)", LargeResponseHandler, dict(path=self.get_plugin_data_folder(),
as_attachment=True,
path_validation=path_validation_factory(lambda path: not is_hidden_path(path),
status_code=404),
access_validation=access_validation_factory(app, admin_validator)))
]
def bodysize_hook(self, current_max_body_sizes, *args, **kwargs):
# max upload size of 1GB for the restore endpoint
return [("POST", r"/restore", 1024 * 1024 * 1024)]
##~~ CLI hook
def cli_commands_hook(self, cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
@click.command("backup")
@click.option("--exclude", multiple=True,
help="Identifiers of data folders to exclude, e.g. 'uploads' to exclude uploads or "
"'timelapse' to exclude timelapses.")
def backup_command(exclude):
"""
Creates a new backup.
"""
backup_file = "backup-{}.zip".format(time.strftime("%Y%m%d-%H%M%S"))
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
click.echo("Creating backup at {}, please wait...".format(backup_file))
self._create_backup(backup_file,
exclude=exclude,
settings=settings,
plugin_manager=cli_group.plugin_manager,
datafolder=datafolder)
click.echo("Done.")
@click.command("restore")
@click.argument("path")
def restore_command(path):
"""
Restores an existing backup from the backup zip provided as argument.
OctoPrint does not need to run for this to proceed.
"""
settings = octoprint.plugin.plugin_settings_for_settings_plugin("backup", self, settings=cli_group.settings)
plugin_manager = cli_group.plugin_manager
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
# register plugin manager plugin setting overlays
plugin_info = plugin_manager.get_plugin_info("pluginmanager")
if plugin_info and plugin_info.implementation:
default_settings_overlay = dict(plugins=dict())
default_settings_overlay["plugins"]["pluginmanager"] = plugin_info.implementation.get_settings_defaults()
settings.add_overlay(default_settings_overlay, at_end=True)
if not os.path.isabs(path):
datafolder = os.path.join(settings.getBaseFolder("data"), "backup")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
path = os.path.join(datafolder, path)
if not os.path.exists(path):
click.echo(u"Backup {} does not exist".format(path), err=True)
sys.exit(-1)
archive = tempfile.NamedTemporaryFile(delete=False)
archive.close()
shutil.copy(path, archive.name)
path = archive.name
def on_install_plugins(plugins):
if not plugins:
return
force_user = settings.global_get_boolean(["plugins", "pluginmanager", "pip_force_user"])
pip_args = settings.global_get(["plugins", "pluginmanager", "pip_args"])
def log(line):
click.echo(u"\t{}".format(line))
for plugin in plugins:
octoprint_compatible = is_octoprint_compatible(*plugin["compatibility"]["octoprint"])
os_compatible = is_os_compatible(plugin["compatibility"]["os"])
compatible = octoprint_compatible and os_compatible
if not compatible:
if not octoprint_compatible and not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint and the underlying operating system".format(plugin["id"]))
elif not octoprint_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to this version of "
u"OctoPrint".format(plugin["id"]))
elif not os_compatible:
click.echo(u"Cannot install plugin {}, it is incompatible to the underlying "
u"operating system".format(plugin["id"]))
continue
click.echo(u"Installing plugin {}".format(plugin["id"]))
self.__class__._install_plugin(plugin,
force_user=force_user,
pip_args=pip_args,
on_log=log)
def on_report_unknown_plugins(plugins):
if not plugins:
return
click.echo(u"The following plugins were not found in the plugin repository. You'll need to install them manually.")
for plugin in plugins:
click.echo(u"\t{} (Homepage: {})".format(plugin["name"], plugin["url"] if plugin["url"] else "?"))
def on_log_progress(line):
click.echo(line)
def on_log_error(line, exc_info=None):
click.echo(line, err=True)
if exc_info is not None:
exc_type, exc_value, exc_tb = exc_info
output = traceback.format_exception(exc_type, exc_value, exc_tb)
for line in output:
click.echo(line.rstrip(), err=True)
if self._restore_backup(path,
settings=settings,
plugin_manager=plugin_manager,
datafolder=datafolder,
on_install_plugins=on_install_plugins,
on_report_unknown_plugins=on_report_unknown_plugins,
on_log_progress=on_log_progress,
on_log_error=on_log_error,
on_invalid_backup=on_log_error):
click.echo(u"Restored from {}".format(path))
else:
click.echo(u"Restoring from {} failed".format(path), err=True)
return [backup_command, restore_command]
##~~ helpers
def _get_backups(self):
backups = []
for entry in scandir(self.get_plugin_data_folder()):
if is_hidden_path(entry.path):
continue
if not entry.is_file():
continue
if not entry.name.endswith(".zip"):
continue
backups.append(dict(name=entry.name,
date=entry.stat().st_mtime,
size=entry.stat().st_size,
url=flask.url_for("index") + "plugin/backup/download/" + entry.name))
return backups
def _get_unknown_plugins(self):
data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE)
if os.path.exists(data_file):
try:
with codecs.open(data_file, mode="r", encoding="utf-8") as f:
unknown_plugins = json.load(f)
assert isinstance(unknown_plugins, list)
assert all(map(lambda x: isinstance(x, dict) and "key" in x and "name" in x and "url" in x, unknown_plugins))
installed_plugins = self._plugin_manager.plugins
unknown_plugins = filter(lambda x: x["key"] not in installed_plugins, unknown_plugins)
if not unknown_plugins:
# no plugins left uninstalled, delete data file
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
return unknown_plugins
except:
self._logger.exception(u"Error while reading list of unknown plugins from {}".format(data_file))
try:
os.remove(data_file)
except:
self._logger.exception(u"Error while deleting list of unknown plugins at {}".format(data_file))
return []
@classmethod
def _clean_dir_backup(cls, basedir,
on_log_progress=None):
basedir_backup = basedir + ".bck"
if os.path.exists(basedir_backup):
def remove_bck():
if callable(on_log_progress):
on_log_progress(u"Found config folder backup from prior restore, deleting it...")
shutil.rmtree(basedir_backup)
if callable(on_log_progress):
on_log_progress(u"... deleted.")
thread = threading.Thread(target=remove_bck)
thread.daemon = True
thread.start()
@classmethod
def _get_disk_size(cls, path):
total = 0
for entry in scandir(path):
if entry.is_dir():
total += cls._get_disk_size(entry.path)
elif entry.is_file():
total += entry.stat().st_size
return total
@classmethod
def _free_space(cls, path, size):
from psutil import disk_usage
return disk_usage(path).free > size
@classmethod
def _get_plugin_repository_data(cls, url, logger=None):
if logger is None:
logger = logging.getLogger(__name__)
try:
r = requests.get(url, timeout=30)
r.raise_for_status()
except:
logger.exception(u"Error while fetching the plugin repository data from {}".format(url))
return dict()
from octoprint.plugins.pluginmanager import map_repository_entry
return dict((plugin["id"], plugin) for plugin in map(map_repository_entry, r.json()))
@classmethod
def _install_plugin(cls, plugin, force_user=False, pip_args=None, on_log=None):
if pip_args is None:
pip_args = []
if on_log is None:
on_log = logging.getLogger(__name__).info
# prepare pip caller
def log(prefix, *lines):
for line in lines:
on_log(u"{} {}".format(prefix, line.rstrip()))
def log_call(*lines):
log(u">", *lines)
def log_stdout(*lines):
log(u"<", *lines)
def log_stderr(*lines):
log(u"!", *lines)
if cls._pip_caller is None:
cls._pip_caller = LocalPipCaller(force_user=force_user)
cls._pip_caller.on_log_call = log_call
cls._pip_caller.on_log_stdout = log_stdout
cls._pip_caller.on_log_stderr = log_stderr
# install plugin
pip = ["install", sarge.shell_quote(plugin["archive"]), '--no-cache-dir']
if plugin.get("follow_dependency_links"):
pip.append("--process-dependency-links")
if force_user:
pip.append("--user")
if pip_args:
pip += pip_args
cls._pip_caller.execute(*pip)
@classmethod
def _create_backup(cls, name,
exclude=None,
settings=None,
plugin_manager=None,
datafolder=None,
on_backup_start=None,
on_backup_done=None,
on_backup_error=None):
try:
if exclude is None:
exclude = []
configfile = settings._configfile
basedir = settings._basedir
temporary_path = os.path.join(datafolder, ".{}".format(name))
final_path = os.path.join(datafolder, name)
size = cls._get_disk_size(basedir)
if not cls._free_space(os.path.dirname(temporary_path), size):
raise InsufficientSpace()
own_folder = datafolder
defaults = [os.path.join(basedir, "config.yaml"),] + \
[os.path.join(basedir, folder) for folder in default_settings["folder"].keys()]
compression = zipfile.ZIP_DEFLATED if zlib else zipfile.ZIP_STORED
if callable(on_backup_start):
on_backup_start(name, temporary_path, exclude)
with zipfile.ZipFile(temporary_path, mode="w", compression=compression, allowZip64=True) as zip:
def add_to_zip(source, target, ignored=None):
if ignored is None:
ignored = []
if source in ignored:
return
if os.path.isdir(source):
for entry in scandir(source):
add_to_zip(entry.path, os.path.join(target, entry.name), ignored=ignored)
elif os.path.isfile(source):
zip.write(source, arcname=target)
# add metadata
metadata = dict(version=get_octoprint_version_string(),
excludes=exclude)
zip.writestr("metadata.json", json.dumps(metadata))
# backup current config file
add_to_zip(configfile, "basedir/config.yaml", ignored=[own_folder,])
# backup configured folder paths
for folder in default_settings["folder"].keys():
if folder in exclude:
continue
if folder in ("generated", "logs", "watched",):
continue
add_to_zip(settings.global_get_basefolder(folder),
"basedir/" + folder.replace("_", "/"),
ignored=[own_folder,])
# backup anything else that might be lying around in our basedir
add_to_zip(basedir, "basedir", ignored=defaults + [own_folder, ])
# add list of installed plugins
plugins = []
plugin_folder = settings.global_get_basefolder("plugins")
for key, plugin in plugin_manager.plugins.items():
if plugin.bundled or (isinstance(plugin.origin, FolderOrigin) and plugin.origin.folder == plugin_folder):
# ignore anything bundled or from the plugins folder we already include in the backup
continue
plugins.append(dict(key=plugin.key,
name=plugin.name,
url=plugin.url))
if len(plugins):
zip.writestr("plugin_list.json", json.dumps(plugins))
os.rename(temporary_path, final_path)
if callable(on_backup_done):
on_backup_done(name, final_path, exclude)
except:
if callable(on_backup_error):
exc_info = sys.exc_info()
try:
on_backup_error(name, exc_info)
finally:
del exc_info
raise
@classmethod
def _restore_backup(cls, path,
settings=None,
plugin_manager=None,
datafolder=None,
on_install_plugins=None,
on_report_unknown_plugins=None,
on_invalid_backup=None,
on_log_progress=None,
on_log_error=None,
on_restore_start=None,
on_restore_done=None,
on_restore_failed=None):
if not is_os_compatible(["!windows"]):
if callable(on_log_error):
on_log_error(u"Restore is not supported on this operating system")
if callable(on_restore_failed):
on_restore_failed(path)
return False
restart_command = settings.global_get(["server", "commands", "serverRestartCommand"])
basedir = settings._basedir
cls._clean_dir_backup(basedir,
on_log_progress=on_log_progress)
plugin_repo = dict()
repo_url = settings.global_get(["plugins", "pluginmanager", "repository"])
if repo_url:
plugin_repo = cls._get_plugin_repository_data(repo_url)
if callable(on_restore_start):
on_restore_start(path)
try:
with zipfile.ZipFile(path, "r") as zip:
# read metadata
try:
metadata_zipinfo = zip.getinfo("metadata.json")
except KeyError:
if callable(on_invalid_backup):
on_invalid_backup(u"Not an OctoPrint backup, lacks metadata.json")
if callable(on_restore_failed):
on_restore_failed(path)
return False
metadata_bytes = zip.read(metadata_zipinfo)
metadata = json.loads(metadata_bytes)
backup_version = get_comparable_version(metadata["version"], base=True)
if backup_version > get_octoprint_version(base=True):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup is from a newer version of OctoPrint and cannot be applied")
if callable(on_restore_failed):
on_restore_failed(path)
return False
# unzip to temporary folder
temp = tempfile.mkdtemp()
try:
if callable(on_log_progress):
on_log_progress(u"Unpacking backup to {}...".format(temp))
abstemp = os.path.abspath(temp)
for member in zip.infolist():
abspath = os.path.abspath(os.path.join(temp, member.filename))
if abspath.startswith(abstemp):
zip.extract(member, temp)
# sanity check
configfile = os.path.join(temp, "basedir", "config.yaml")
if not os.path.exists(configfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks config.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
import yaml
with codecs.open(configfile) as f:
configdata = yaml.safe_load(f)
if configdata.get("accessControl", dict()).get("enabled", True):
userfile = os.path.join(temp, "basedir", "users.yaml")
if not os.path.exists(userfile):
if callable(on_invalid_backup):
on_invalid_backup(u"Backup lacks users.yaml")
if callable(on_restore_failed):
on_restore_failed(path)
return False
if callable(on_log_progress):
on_log_progress(u"Unpacked")
# install available plugins
with codecs.open(os.path.join(temp, "plugin_list.json"), "r") as f:
plugins = json.load(f)
known_plugins = []
unknown_plugins = []
if plugins:
if plugin_repo:
for plugin in plugins:
if plugin["key"] in plugin_manager.plugins:
# already installed
continue
if plugin["key"] in plugin_repo:
# not installed, can be installed from repository url
known_plugins.append(plugin_repo[plugin["key"]])
else:
# not installed, not installable
unknown_plugins.append(plugin)
else:
# no repo, all plugins are not installable
unknown_plugins = plugins
if callable(on_log_progress):
if known_plugins:
on_log_progress(u"Known and installable plugins: {}".format(u", ".join(map(lambda x: x["id"], known_plugins))))
if unknown_plugins:
on_log_progress(u"Unknown plugins: {}".format(u", ".join(map(lambda x: x["key"], unknown_plugins))))
if callable(on_install_plugins):
on_install_plugins(known_plugins)
if callable(on_report_unknown_plugins):
on_report_unknown_plugins(unknown_plugins)
# move config data
basedir_backup = basedir + ".bck"
basedir_extracted = os.path.join(temp, "basedir")
if callable(on_log_progress):
on_log_progress(u"Renaming {} to {}...".format(basedir, basedir_backup))
os.rename(basedir, basedir_backup)
try:
if callable(on_log_progress):
on_log_progress(u"Moving {} to {}...".format(basedir_extracted, basedir))
os.rename(basedir_extracted, basedir)
except:
if callable(on_log_error):
on_log_error(u"Error while restoring config data", exc_info=sys.exc_info())
on_log_error(u"Rolling back old config data")
os.rename(basedir_backup, basedir)
if callable(on_restore_failed):
on_restore_failed(path)
return False
if unknown_plugins:
if callable(on_log_progress):
on_log_progress(u"Writing info file about unknown plugins")
if not os.path.isdir(datafolder):
os.makedirs(datafolder)
unknown_plugins_path = os.path.join(datafolder, UNKNOWN_PLUGINS_FILE)
try:
with codecs.open(unknown_plugins_path, mode="w", encoding="utf-8") as f:
json.dump(unknown_plugins, f)
except:
if callable(on_log_error):
on_log_error(u"Could not persist list of unknown plugins to {}".format(unknown_plugins_path),
exc_info = sys.exc_info())
finally:
if callable(on_log_progress):
on_log_progress(u"Removing temporary unpacked folder")
shutil.rmtree(temp)
except:
exc_info = sys.exc_info()
try:
if callable(on_log_error):
on_log_error(u"Error while running restore", exc_info=exc_info)
if callable(on_restore_failed):
on_restore_failed(path)
finally:
del exc_info
return False
finally:
# remove zip
if callable(on_log_progress):
on_log_progress(u"Removing temporary zip")
os.remove(path)
# restart server
if restart_command:
import sarge
if callable(on_log_progress):
on_log_progress(u"Restarting...")
if callable(on_restore_done):
on_restore_done(path)
try:
sarge.run(restart_command, async_=True)
except:
if callable(on_log_error):
on_log_error(u"Error while restarting via command {}".format(restart_command),
exc_info=sys.exc_info())
on_log_error(u"Please restart OctoPrint manually")
return False
else:
if callable(on_restore_done):
on_restore_done(path)
return True
def _send_client_message(self, message, payload=None):
if payload is None:
payload = dict()
payload["type"] = message
self._plugin_manager.send_plugin_message(self._identifier, payload)
class InsufficientSpace(Exception):
pass
__plugin_name__ = gettext(u"Backup & Restore")
__plugin_author__ = u"Gina Häußge"
__plugin_description__ = u"Backup & restore your OctoPrint settings and data"
__plugin_disabling_discouraged__ = gettext(u"Without this plugin you will no longer be able to backup "
u"& restore your OctoPrint settings and data.")
__plugin_license__ = u"AGPLv3"
__plugin_implementation__ = BackupPlugin()
__plugin_hooks__ = {
"octoprint.server.http.routes": __plugin_implementation__.route_hook,
"octoprint.server.http.bodysize": __plugin_implementation__.bodysize_hook,
"octoprint.cli.commands": __plugin_implementation__.cli_commands_hook
}
@@ -0,0 +1,52 @@
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["OctoPrintClient"], factory);
} else {
factory(global.OctoPrintClient);
}
})(this, function(OctoPrintClient) {
var OctoPrintBackupClient = function(base) {
this.base = base;
this.url = this.base.getBlueprintUrl("backup");
};
OctoPrintBackupClient.prototype.get = function(refresh, opts) {
return this.base.get(this.url, opts);
};
OctoPrintBackupClient.prototype.createBackup = function(exclude, opts) {
exclude = exclude || [];
var data = {
exclude: exclude
};
return this.base.postJson(this.url + "backup", data, opts);
};
OctoPrintBackupClient.prototype.deleteBackup = function(backup, opts) {
return this.base.delete(this.url + "backup/" + backup, opts);
};
OctoPrintBackupClient.prototype.restoreBackup = function(backup, opts) {
var data = {
path: backup
};
return this.base.postJson(this.url + "restore", data, opts);
};
OctoPrintBackupClient.prototype.restoreBackupFromUpload = function (file, data) {
data = data || {};
var filename = data.filename || undefined;
return this.base.upload(this.url + "restore", file, filename, data);
};
OctoPrintBackupClient.prototype.deleteUnknownPlugins = function (opts) {
return this.base.delete(this.url + "unknown_plugins", opts);
};
OctoPrintClient.registerPluginComponent("backup", OctoPrintBackupClient);
return OctoPrintBackupClient;
});
@@ -0,0 +1 @@
#settings_plugin_backup_backup_table .settings_plugin_backup_actions{width:75px;text-align:center}#settings_plugin_backup_backup_table .settings_plugin_backup_actions a{color:#000}#settings_plugin_backup_backup_table .settings_plugin_backup_date{width:200px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_size{width:100px;text-align:right}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox{text-align:center;width:10px}#settings_plugin_backup_backup_table .settings_plugin_backup_checkbox input[type=checkbox]{margin-top:0}#settings_plugin_backup_restoredialog_output .message{font-weight:700}#settings_plugin_backup_restoredialog_output .error{font-weight:700;color:#900}#settings_plugin_backup_restoredialog_output .stdout{color:#333}#settings_plugin_backup_restoredialog_output .stderr{color:#900}#settings_plugin_backup_restoredialog_output .call{color:#009}
@@ -0,0 +1,289 @@
$(function() {
function BackupViewModel(parameters) {
var self = this;
self.loginState = parameters[0];
self.settings = parameters[1];
self.backups = new ItemListHelper(
"plugin.backup.backups",
{
"date": function (a, b) {
// sorts descending
if (a["date"] > b["date"]) return -1;
if (a["date"] < b["date"]) return 1;
return 0;
}
},
{
},
"date",
[],
[],
10
);
self.markedForBackupDeletion = ko.observableArray([]);
self.excludeFromBackup = ko.observableArray([]);
self.backupInProgress = ko.observable(false);
self.restoreSupported = ko.observable(true);
self.backupUploadButton = $("#settings-backup-upload");
self.backupUploadData = undefined;
self.backupUploadButton.fileupload({
dataType: "json",
maxNumberOfFiles: 1,
autoUpload: false,
headers: OctoPrint.getRequestHeaders(),
add: function(e, data) {
if (data.files.length === 0) {
// no files? ignore
return false;
}
self.backupUploadName(data.files[0].name);
self.backupUploadData = data;
},
done: function(e, data) {
self.backupUploadName(undefined);
self.backupUploadData = undefined;
}
});
self.backupUploadName = ko.observable();
self.restoreInProgress = ko.observable(false);
self.restoreTitle = ko.observable();
self.restoreDialog = undefined;
self.restoreOutput = undefined;
self.unknownPlugins = ko.observableArray([]);
self.loglines = ko.observableArray([]);
self.requestData = function() {
OctoPrint.plugins.backup.get()
.done(self.fromResponse);
};
self.fromResponse = function(response) {
self.backups.updateItems(response.backups);
self.unknownPlugins(response.unknown_plugins);
self.restoreSupported(response.restore_supported);
};
self.createBackup = function() {
var excluded = self.excludeFromBackup();
OctoPrint.plugins.backup.createBackup(excluded)
.done(function() {
self.excludeFromBackup([]);
})
};
self.removeBackup = function(backup) {
var perform = function() {
OctoPrint.plugins.backup.deleteBackup(backup)
.done(function() {
self.requestData();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
perform);
};
self.restoreBackup = function(backup) {
if (!self.restoreSupported()) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Preparing to restore...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
perform);
};
self.performRestoreFromUpload = function() {
if (self.backupUploadData === undefined) return;
var perform = function() {
self.restoreInProgress(true);
self.loglines.removeAll();
self.loglines.push({line: "Uploading backup, this can take a while. Please wait...", stream: "message"});
self.loglines.push({line: " ", stream: "message"});
self.restoreDialog.modal({keyboard: false, backdrop: "static", show: true});
self.backupUploadData.submit();
};
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: self.backupUploadName()}),
perform);
};
self.deleteUnknownPluginRecord = function() {
var perform = function() {
OctoPrint.plugins.backup.deleteUnknownPlugins()
.done(function() {
self.requestData();
});
};
showConfirmationDialog(gettext("You are about to delete the record of plugins unknown during the last restore."),
perform);
};
self.markFilesOnPage = function() {
self.markedForBackupDeletion(_.uniq(self.markedForBackupDeletion().concat(_.map(self.backups.paginatedItems(), "name"))));
};
self.markAllFiles = function() {
self.markedForBackupDeletion(_.map(self.backups.allItems, "name"));
};
self.clearMarkedFiles = function() {
self.markedForBackupDeletion.removeAll();
};
self.removeMarkedFiles = function() {
var perform = function() {
self._bulkRemove(self.markedForBackupDeletion())
.done(function() {
self.markedForBackupDeletion.removeAll();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete %(count)d backups."), {count: self.markedForBackupDeletion().length}),
perform);
};
self.onStartup = function() {
self.restoreDialog = $("#settings_plugin_backup_restoredialog");
self.restoreOutput = $("#settings_plugin_backup_restoredialog_output");
};
self.onSettingsShown = function() {
self.requestData();
};
self.onDataUpdaterPluginMessage = function(plugin, data) {
if (plugin !== "backup") return;
if (data.type === "backup_done") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Backup created successfully"),
type: "success"
});
} else if (data.type === "backup_started") {
self.backupInProgress(true);
} else if (data.type === "backup_error") {
self.requestData();
self.backupInProgress(false);
new PNotify({
title: gettext("Creating the backup failed"),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error:data.error}),
type: "error",
hide: false
});
} else if (data.type === "restore_started") {
self.loglines.push({line: gettext("Restoring from backup..."), stream: "message"});
self.loglines.push({line: " ", stream: "message"});
} else if (data.type === "restore_failed") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore failed! Check the above output and octoprint.log for reasons as to why."), stream: "error"});
self.restoreInProgress(false);
} else if (data.type === "restore_done") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: gettext("Restore successful! The server will now be restarted!"), stream: "message"});
self.restoreInProgress(false);
} else if (data.type === "install_plugin") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
stream: "message"
});
} else if (data.type === "plugin_incompatible") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: data.plugin.key}),
stream: "stderr"
});
} else if (data.type === "unknown_plugins") {
if (data.plugins.length > 0) {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({line: _.sprintf(gettext("There are %(count)d plugins you'll need to install manually since they aren't registered on the repository:"), {count: data.plugins.length}), stream: "message"});
_.each(data.plugins, function(plugin) {
self.loglines.push({line: plugin.name + ": " + plugin.url, stream: "message"});
});
self.loglines.push({line: " ", stream: "message"});
self.unknownPlugins(data.plugins);
}
} else if (data.type === "logline") {
self.loglines.push(self._preprocessLine({line: data.line, stream: data.stream}));
self._scrollRestoreOutputToEnd();
}
};
self._scrollRestoreOutputToEnd = function() {
self.restoreOutput.scrollTop(self.restoreOutput[0].scrollHeight - self.restoreOutput.height());
};
self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./;
self._preprocessLine = function(line) {
if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) {
line.stream = "stdout";
}
return line;
};
self._bulkRemove = function(files) {
var title, message, handler;
title = gettext("Deleting backups");
message = _.sprintf(gettext("Deleting %(count)d backups..."), {count: files.length});
handler = function(filename) {
return OctoPrint.plugins.backup.deleteBackup(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
})
.fail(function(jqXHR) {
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: filename});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: filename, error: jqXHR.responseText});
deferred.notify(short, long, false);
});
};
var deferred = $.Deferred();
var promise = deferred.promise();
var options = {
title: title,
message: message,
max: files.length,
output: true
};
showProgressModal(options, promise);
var requests = [];
_.each(files, function(filename) {
var request = handler(filename);
requests.push(request)
});
$.when.apply($, _.map(requests, wrapPromiseWithAlways))
.done(function() {
deferred.resolve();
self.requestData();
});
return promise;
};
}
OCTOPRINT_VIEWMODELS.push({
construct: BackupViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel"],
elements: ["#settings_plugin_backup"]
});
});
@@ -0,0 +1,52 @@
#settings_plugin_backup_backup_table {
.settings_plugin_backup_name {
}
.settings_plugin_backup_actions {
width: 75px;
text-align: center;
a {
color: black;
}
}
.settings_plugin_backup_date {
width: 200px;
text-align: right;
}
.settings_plugin_backup_size {
width: 100px;
text-align: right;
}
.settings_plugin_backup_checkbox {
text-align: center;
width: 10px;
input[type="checkbox"] {
margin-top: 0;
}
}
}
#settings_plugin_backup_restoredialog_output {
.message {
font-weight: bold;
}
.error {
font-weight: bold;
color: #990000;
}
.stdout {
color: #333333;
}
.stderr {
color: #990000;
}
.call {
color: #000099;
}
}
@@ -0,0 +1,135 @@
<div class="alert" data-bind="visible: unknownPlugins().length > 0">
{% trans %}
Some plugins during the last restore could not be identified and hence not automatically installed.
Please install them manually, they are listed below including their stated homepages:
{% endtrans %}
<ul data-bind="foreach: unknownPlugins">
<li><span data-bind="text: name"></span>: <a data-bind="text: url, attr: {href: url}" target="_blank" rel="noreferrer noopener"></a></li>
</ul>
<small><a href="javascript:void(0)" data-bind="click: deleteUnknownPluginRecord">{{ _('Delete record of unknown plugins') }}</a></small>
</div>
<h3>{{ _('Existing backups') }}</h3>
<div data-bind="visible: backups.allSize() <= 0">
<p>{{ _('There are no backups. Maybe create one below?') }}</p>
</div>
<div data-bind="visible: backups.allSize() > 0">
<p>{{ _('These are the backups of your settings and files that already exist on this OctoPrint instance. You may delete, download or restore them.') }}</p>
<div class="pull-left">
<div class="btn-group">
<button class="btn btn-small dropdown-toggle" data-toggle="dropdown"><i class="fa fa-square-o"></i> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="javascript:void(0)" data-bind="click: markFilesOnPage">{{ _('Select all on this page') }}</a></li>
<li><a href="javascript:void(0)" data-bind="click: markAllFiles">{{ _('Select all') }}</a></li>
<li class="divider"></li>
<li><a href="javascript:void(0)" data-bind="click: clearMarkedFiles">{{ _('Clear selection') }}</a></li>
</ul>
</div>
<button class="btn btn-small" data-bind="click: removeMarkedFiles, enable: markedForBackupDeletion().length > 0">{{ _('Delete selected') }}</button>
</div>
<table class="table table-condensed table-hover" id="settings_plugin_backup_backup_table">
<thead>
<tr>
<th class="settings_plugin_backup_checkbox"></th>
<th class="settings_plugin_backup_name">{{ _('Name') }}</th>
<th class="settings_plugin_backup_date">{{ _('Date') }}</th>
<th class="settings_plugin_backup_size">{{ _('Size') }}</th>
<th class="settings_plugin_backup_actions">{{ _('Action') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: backups.paginatedItems">
<tr>
<td class="settings_plugin_backup_checkbox"><input type="checkbox" data-bind="value: name, checked: $root.markedForBackupDeletion"></td>
<td class="settings_plugin_backup_name" data-bind="text: name"></td>
<td class="settings_plugin_backup_date" data-bind="text: formatDate(date)"></td>
<td class="settings_plugin_backup_size" data-bind="text: formatSize(size)"></td>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete') }}" class="fa fa-trash-o" data-bind="click: function() { $parent.removeBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"></a>&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Download') }}" class="fa fa-download" data-bind="attr: {href: url}"></a><span data-bind="visible: $parent.restoreSupported()">&nbsp;|&nbsp;<a href="javascript:void(0)" title="{{ _('Restore') }}" data-bind="click: function() { $parent.restoreBackup($data.name) }, css: {disabled: $root.backupInProgress() || $root.restoreInProgress()"><i class="fa fa-refresh"></i></a></span></td>
</tr>
</tbody>
</table>
<div class="pagination pagination-mini pagination-centered">
<ul>
<li data-bind="css: {disabled: backups.currentPage() === 0}"><a href="javascript:void(0)" data-bind="click: backups.prevPage">«</a></li>
</ul>
<ul data-bind="foreach: backups.pages">
<li data-bind="css: { active: $data.number === $root.backups.currentPage(), disabled: $data.number === -1 }"><a href="javascript:void(0)" data-bind="text: $data.text, click: function() { $root.backups.changePage($data.number); }"></a></li>
</ul>
<ul>
<li data-bind="css: {disabled: backups.currentPage() === backups.lastPage()}"><a href="javascript:void(0)" data-bind="click: backups.nextPage">»</a></li>
</ul>
</div>
</div>
<h3>{{ _('Create backup') }}</h3>
<p>{{ _('Create a new backup of the current state.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'uploads', checked: excludeFromBackup"> {{ _('Exclude uploaded files & metadata from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="value: 'timelapse', checked: excludeFromBackup"> {{ _('Exclude timelapses from backup') }}
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: createBackup"><i class="fa fa-spinner fa-spin" data-bind="visible: backupInProgress"></i> {{ _('Create backup now') }}</button>
</div>
</div>
</form>
<div data-bind="visible: restoreSupported()">
<h3>{{ _('Restore from uploaded backup') }}</h3>
<p>{{ _('Restore settings & files from an uploaded backup archive.') }}</p>
<form class="form-horizontal">
<div class="control-group">
<label class="control-label">{{ _('Backup file') }}</label>
<div class="controls">
<div class="input-prepend">
<span class="btn fileinput-button">
<span>{{ _('Browse...') }}</span>
<input id="settings-backup-upload" type="file" name="file" data-url="{{ url_for("plugin.backup.perform_restore") }}" accept=".zip">
</span>
<span class="add-on" data-bind="text: backupUploadName"></span>
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-primary" data-bind="enable: !backupInProgress() && !restoreInProgress(), click: performRestoreFromUpload"><i class="fa fa-spinner fa-spin" data-bind="visible: restoreInProgress"></i> {{ _('Upload & restore') }}</button>
</div>
</div>
</form>
</div>
<div data-bind="visible: !restoreSupported()">
{{ _('Please note that the operating system that this OctoPrint server is running on does not support automatically restoring backups. You will have to <a href="%(url)s" target="_blank" rel="noopener noreferrer">restore your backups manually for now</a>.', url='https://faq.octoprint.org/manual-restore') }}
</div>
<div id="settings_plugin_backup_restoredialog" class="modal hide fade">
<div class="modal-header">
<h3>{{ _('Restoring from backup...') }}</h3>
</div>
<div class="modal-body">
<pre id="settings_plugin_backup_restoredialog_output" class="pre-scrollable pre-output" style="height: 170px" data-bind="foreach: loglines"><span data-bind="text: line, css: {stdout: stream == 'stdout', stderr: stream == 'stderr', call: stream == 'call', message: stream == 'message', error: stream == 'error'}"></span></pre>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" data-bind="enable: !$root.restoreInProgress()" aria-hidden="true">{{ _('Close') }}</button>
</div>
</div>
@@ -1,14 +1,22 @@
<h3>{{ _('Access Control') }}</h3>
{% trans %}<p>
{% trans safe_remote_url='https://octoprint.org/blog/2018/09/03/safe-remote-access/' %}<p>
<strong>Please read the following, it is very important for your printer's health!</strong>
</p>
<p>
OctoPrint by default ships with Access Control enabled, meaning you won't be able to do anything with the
printer unless you login first as a configured user. This is to <strong>prevent strangers - possibly with
malicious intent - to gain access to your printer</strong> via the internet or another untrustworthy network
malicious intent - to gain access to your printer</strong> via an untrustworthy network
and using it in such a way that it is damaged or worse (i.e. causes a fire).
</p>
<p>
If you plan on accessing OctoPrint remotely over the internet, <strong>you should not only rely on the built-in
Access Control mechanisms</strong> however -
<a href="{{ safe_remote_url }}" target="_blank" rel="noopener noreferrer">take additional precautions</a>.
Your OctoPrint enabled printer is a critical home appliance you really should not give anyone who happens to be
connected to the internet access to - even read-only! <strong>An instance available publicly on the internet
will be found, and people will try to break it open.</strong>
</p>
<p>
It looks like you haven't configured access control yet. Please <strong>set up a username and password</strong> for the
initial administrator account who will have full access to both the printer and OctoPrint's settings, then click
@@ -36,12 +44,12 @@
</div>
</form>
{% trans %}<p>
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy network and you don't
<strong>Note:</strong> In case that your OctoPrint installation is only accessible from within a trustworthy local network and you don't
need Access Control for other reasons, you may alternatively disable Access Control. You should only
do this if you are absolutely certain that only people you know and trust will be able to connect to it.
</p>
<p>
<strong>Do NOT underestimate the risk of an unsecured access from the internet to your printer!</strong>
<strong>Do NOT underestimate the risk of access from the internet to your printer and OctoPrint instance!</strong>
</p>{% endtrans %}
<div class="row-fluid">
+1 -1
View File
@@ -312,7 +312,7 @@ class CuraPlugin(octoprint.plugin.SlicerPlugin,
working_dir))
import sarge
p = sarge.run(args, cwd=working_dir, async=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p = sarge.run(args, cwd=working_dir, async_=True, stdout=sarge.Capture(), stderr=sarge.Capture())
p.wait_events()
self._slicing_commands[machinecode_path] = p.commands[0]
+9 -8
View File
@@ -359,6 +359,8 @@ class Profile(object):
regex_print_temperature = re.compile("print_temperature(\d?)")
regex_strip_comments = re.compile(";.*$", flags=re.MULTILINE)
regex_broken_replacements = re.compile("\?([a-zA-Z0-9_]*)\?")
@classmethod
def from_cura_ini(cls, path):
import logging
@@ -685,9 +687,9 @@ class Profile(object):
gcode = defaults[key]
if key in ("start_gcode", "end_gcode"):
return gcode[extruder_count-1]
return self.regex_broken_replacements.sub("{\\1}", gcode[extruder_count-1])
else:
return gcode
return self.regex_broken_replacements.sub("{\\1}", gcode)
def get_profile_string(self):
import base64
@@ -749,17 +751,16 @@ class Profile(object):
if key == "start_gcode":
contents = self.get_gcode_template("start_gcode", extruder_count=extruder_count)
prefix += self.get_start_gcode_prefix(contents)
prefix += self.get_start_gcode_prefix(contents, extruder_count=extruder_count)
else:
contents = self.get_gcode_template(key, extruder_count=extruder_count)
return unicode(prefix + re.sub("(.)\{([^\}]*)\}", self.replaceTagMatch, contents).rstrip() + '\n' + postfix).strip().encode('utf-8') + '\n'
def get_start_gcode_prefix(self, contents):
extruder_count = self.get_int("extruder_amount")
def get_start_gcode_prefix(self, contents, extruder_count=1):
prefix = ""
without_comments = Profile.regex_strip_comments.sub("", contents)
gcode_parameter_key = "S"
if self.get("gcode_flavor") == GcodeFlavors.MACH3:
@@ -773,12 +774,12 @@ class Profile(object):
bed_temp = 0
if self.get_boolean("has_heated_bed"):
bed_temp = self.get_float("print_bed_temperature")
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in Profile.regex_strip_comments.sub("", contents)
include_bed_temp = bed_temp > 0 and not "{print_bed_temperature}" in without_comments
if include_bed_temp:
prefix += "M140 {param}{bed_temp}\n".format(param=gcode_parameter_key, bed_temp=bed_temp)
if temp > 0 and not "{print_temperature}" in Profile.regex_strip_comments.sub("", contents):
if temp > 0 and not "{print_temperature}" in without_comments:
if extruder_count > 0:
def temp_line(temp, extruder, param, template):
t = temp
@@ -181,6 +181,15 @@ $(function() {
self.uploadDialog.modal("hide");
self.requestData();
self.slicingViewModel.requestData();
},
error: function(jqXHR, textStatus, errorThrown) {
self.uploadBusy(false);
new PNotify({
title: gettext("Profile import failed"),
text: gettext("Could not import the provided profile, it might be invalid. Check <code>octoprint.log</code> for details"),
type: "error",
hide: false
});
}
});
@@ -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>
+24 -5
View File
@@ -194,8 +194,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
params["txtRecord"] = pybonjour.TXTRecord(txt_record)
key = (reg_type, port)
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self._logger.info(u"Registered {name} for {reg_type}".format(**locals()))
counter = 1
while True:
try:
self._sd_refs[key] = pybonjour.DNSServiceRegister(**params)
self._logger.info(u"Registered '{name}' for {regtype}".format(**params))
return True
except pybonjour.BonjourError as be:
if be.errorCode == pybonjour.kDNSServiceErr_NameConflict:
# Name already registered by different service, let's try a counter postfix. See #2852
counter += 1
params["name"] = u"{} ({})".format(name, counter)
else:
raise
def zeroconf_unregister(self, reg_type, port=None):
"""
@@ -601,8 +613,14 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
alive message
"""
from BaseHTTPServer import BaseHTTPRequestHandler
from StringIO import StringIO
try:
# noinspection PyCompatibility
from http.server import BaseHTTPRequestHandler
except ImportError:
# noinspection PyCompatibility
from BaseHTTPServer import BaseHTTPRequestHandler
from io import BytesIO
import socket
socket.setdefaulttimeout(timeout)
@@ -617,8 +635,9 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
class Request(BaseHTTPRequestHandler):
# noinspection PyMissingConstructor
def __init__(self, request_text):
self.rfile = StringIO(request_text)
self.rfile = BytesIO(request_text)
self.raw_requestline = self.rfile.readline()
self.error_code = self.error_message = None
self.parse_request()
@@ -0,0 +1,183 @@
# 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
import flask
import flask_login
from flask_babel import gettext
from collections import defaultdict
import threading
class ForceLoginPlugin(octoprint.plugin.UiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin):
MAX_BACKLOG_LEN = 100
# noinspection PyMissingConstructor
def __init__(self):
self._message_backlog = defaultdict(list)
self._message_backlog_mutex = threading.RLock()
def get_assets(self):
return dict(
js=["js/viewmodel.js"]
)
def will_handle_ui(self, request):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return False
from octoprint.server.util.flask import passive_login
result = passive_login()
if hasattr(result, "status_code") and result.status_code == 200:
# passive login successful, no need to handle that
return False
else:
return True
def on_ui_render(self, now, request, render_kwargs):
from flask import render_template, make_response
"""
Support theming of the login dialog, just in case the core UI is themed as well.
Example usage by a plugin:
def forcelogin_theming():
from flask import url_for
return [url_for("plugin.myplugin.static", filename="css/forcelogin_theme.css")]
__plugin_hooks__ = {
"octoprint.plugin.forcelogin.theming": forcelogin_theming
}
Only a list of ready-made URLs to CSS files is supported, neither LESS nor JS. Best use
url_for like in the example above to be prepared for any configured prefix URLs.
"""
additional_assets = []
for name, hook in self._plugin_manager.get_hooks("octoprint.plugin.forcelogin.theming").items():
try:
assets = hook()
if isinstance(assets, (tuple, list)):
additional_assets += assets
except:
self._logger.exception("Error fetching theming CSS to include from plugin {}".format(name))
render_kwargs.update(dict(forcelogin_theming=additional_assets))
return make_response(render_template("forcelogin_index.jinja2", **render_kwargs))
def get_ui_custom_tracked_files(self):
from os.path import join as opj
paths = [opj("static", "css", "forcelogin.css"),
opj("static", "js", "main.js"),
opj("static", "js", "viewmodel.js"),
opj("static", "less", "forcelogin.less"),
opj("templates", "parts", "forcelogin_css.jinja2"),
opj("templates", "parts", "forcelogin_javascripts.jinja2"),
opj("templates", "forcelogin_index.jinja2")]
return [opj(self._basefolder, path) for path in paths]
def get_ui_preemptive_caching_enabled(self):
return False
def get_before_request_handlers(self):
def check_login_required():
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return
elif not self._user_manager.enabled:
# ACL isn't enabled
return
if flask.request.endpoint in ("api.login",):
return
user = flask_login.current_user
if user is None or user.is_anonymous() or not user.is_active():
return flask.make_response("Forbidden", 403)
return [check_login_required]
def access_validator(self, request):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return
elif not self._user_manager.enabled:
# ACL isn't enabled
return
import tornado.web
from octoprint.server.util.flask import get_flask_user_from_request
user = get_flask_user_from_request(request)
if user is None or not user.is_authenticated():
raise tornado.web.HTTPError(403)
def socket_register_validator(self, socket, user):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return True
elif not self._user_manager.enabled:
# ACL isn't enabled
return True
return user is not None and not user.is_anonymous() and user.is_active()
def socket_authed(self, socket, user):
with self._message_backlog_mutex:
backlog = self._message_backlog.pop(socket, [])
if len(backlog):
for message, payload in backlog:
socket._do_emit(message, payload)
self._logger.debug("Sent backlog of {} message(s) via socket".format(len(backlog)))
def socket_emit_validator(self, socket, user, message, payload):
if self._user_manager.enabled and not self._user_manager.hasBeenCustomized():
# ACL hasn't been configured yet, make an exception
return True
elif not self._user_manager.enabled:
# ACL isn't enabled
return True
if message in ("connected", "reauthRequired"):
return True
if user is not None and not user.is_anonymous() and user.is_active():
return True
with self._message_backlog_mutex:
if len(self._message_backlog[socket]) < self.MAX_BACKLOG_LEN:
self._message_backlog[socket].append((message, payload))
self._logger.debug("Socket message held back until authed, added to backlog: {}".format(message))
else:
self._logger.warn("Socket message held back, but backlog full. Throwing message away: {}".format(message))
return False
__plugin_name__ = "Force Login"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Forces users to login, disables read-only mode."
__plugin_disabling_discouraged__ = gettext("Without this plugin anonymous users will have read-only access to your "
"OctoPrint instance. Only disable this if you are comfortable with this, your "
"OctoPrint instance is not publicly reachable on the internet and you fully "
"trust everyone who has access to your local network!")
__plugin_implementation__ = ForceLoginPlugin()
__plugin_hooks__ = {
"octoprint.server.api.before_request": __plugin_implementation__.get_before_request_handlers,
"octoprint.server.http.access_validator": __plugin_implementation__.access_validator,
"octoprint.server.sockjs.register": __plugin_implementation__.socket_register_validator,
"octoprint.server.sockjs.authed": __plugin_implementation__.socket_authed,
"octoprint.server.sockjs.emit": __plugin_implementation__.socket_emit_validator
}
@@ -0,0 +1 @@
body{padding-top:40px;padding-bottom:40px;background-color:#f5f5f5}.form-signin{max-width:300px;padding:19px 29px 29px;margin:0 auto 20px;background-color:#fff;border:1px solid #e5e5e5;-webkit-border-radius:5px;-moz-border-radius:5px;border-radius:5px;-webkit-box-shadow:0 1px 2px rgba(0,0,0,.05);-moz-box-shadow:0 1px 2px rgba(0,0,0,.05);box-shadow:0 1px 2px rgba(0,0,0,.05)}.form-signin .form-signin-heading,.form-signin .checkbox{margin-bottom:10px}.form-signin input[type=text],.form-signin input[type=password]{font-size:16px;height:auto;margin-bottom:15px;padding:7px 9px}#login-error,#login-offline{display:none}#login-error.in,#login-offline.in{display:block}#login-overlay{position:fixed;top:0;left:0;width:100%;height:100%;z-index:10000;display:none}#login-overlay.in{display:block}#login-overlay .background{position:fixed;top:0;left:0;width:100%;height:100%;background-color:#000;filter:alpha(opacity=50);-moz-opacity:.5;-khtml-opacity:.5;opacity:.5}#login-overlay .wrapper{position:absolute;top:0;bottom:0;left:0;right:0}#login-overlay .wrapper .outer{display:table;width:100%;height:100%}#login-overlay .wrapper .outer .inner{display:table-cell;vertical-align:middle}#login-overlay .wrapper .outer .inner .content{text-align:center;color:#fff}
@@ -0,0 +1,72 @@
/*
* Will get included into the login dialog, NOT into the regular OctoPrint
* web application.
*/
$(function() {
var overlayElement = $("#login-overlay");
var errorElement = $("#login-error");
var offlineElement = $("#login-offline");
var buttonElement = $("#login-button");
var reconnectElement = $("#login-reconnect");
buttonElement.click(function() {
var usernameElement = $("#login-user");
var passwordElement = $("#login-password");
var rememberElement = $("#login-remember");
var username = usernameElement.val();
var password = passwordElement.val();
var remember = rememberElement.checked;
overlayElement.addClass("in");
errorElement.removeClass("in");
OctoPrint.browser.login(username, password, remember)
.done(function() {
location.reload();
})
.fail(function() {
usernameElement.val("");
passwordElement.val("");
overlayElement.removeClass("in");
errorElement.addClass("in");
});
return false;
});
var OctoPrint = window.OctoPrint;
OctoPrint.options.baseurl = BASE_URL;
OctoPrint.socket.onMessage("connected", function(data) {
var payload = data.data;
OctoPrint.options.apikey = payload.apikey;
// update the API key directly in jquery's ajax options too,
// to ensure the fileupload plugin and any plugins still using
// $.ajax directly still work fine too
UI_API_KEY = payload["apikey"];
$.ajaxSetup({
headers: {"X-Api-Key": UI_API_KEY}
});
});
OctoPrint.socket.onConnected = function() {
buttonElement.prop("disabled", false);
offlineElement.removeClass("in");
};
OctoPrint.socket.onDisconnected = function() {
buttonElement.prop("disabled", true);
offlineElement.addClass("in");
};
reconnectElement.click(function() {
OctoPrint.socket.reconnect();
});
OctoPrint.socket.connect();
});
@@ -0,0 +1,17 @@
/*
* View model that takes care to redirect to / on logout in the regular
* OctoPrint web application.
*/
$(function() {
function ForceLoginViewModel(parameters) {
var self = this;
self.onUserLoggedOut = function() {
location.reload();
}
}
// view model class, parameters for constructor, container to bind to
ADDITIONAL_VIEWMODELS.push([ForceLoginViewModel, [], []]);
});
@@ -0,0 +1,90 @@
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
max-width: 300px;
padding: 19px 29px 29px;
margin: 0 auto 20px;
background-color: #fff;
border: 1px solid #e5e5e5;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05);
-moz-box-shadow: 0 1px 2px rgba(0,0,0,.05);
box-shadow: 0 1px 2px rgba(0,0,0,.05);
.form-signin-heading, .checkbox {
margin-bottom: 10px;
}
input[type="text"], input[type="password"] {
font-size: 16px;
height: auto;
margin-bottom: 15px;
padding: 7px 9px;
}
}
#login-error,
#login-offline {
display: none;
&.in {
display: block;
}
}
#login-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 10000;
display: none;
&.in {
display: block;
}
.background {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: #000000;
filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;
}
.wrapper {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
.outer {
display: table;
width: 100%;
height: 100%;
.inner {
display: table-cell;
vertical-align: middle;
.content {
text-align: center;
color: white;
}
}
}
}
}
@@ -0,0 +1,39 @@
<html>
<head>
<title>OctoPrint Login</title>
{% include "parts/forcelogin_css.jinja2" %}
{% include "parts/forcelogin_javascripts.jinja2" %}
</head>
<body>
<div class="container">
<form class="form-signin">
<h2 class="form-signin-heading">{{ _('Please log in') }}</h2>
<div id="login-error" class="alert alert-error">{{ _('Incorrect username or password.') }}</div>
<div id="login-offline" class="alert alert-error">{{ _('Server is currently offline.') }} <a id="login-reconnect" href="javascript:void(0)">{{ _('Reconnect...') }}</a></div>
<input type="text" id="login-user" class="input-block-level" placeholder="{{ _('Username') }}">
<input type="password" id="login-password" class="input-block-level" placeholder="{{ _('Password') }}">
<label class="checkbox">
<input type="checkbox" id="login-remember"> {{ _('Remember me') }}
</label>
<button class="btn btn-block btn-large btn-primary" id="login-button" type="submit">{{ _('Log in') }}</button>
</form>
</div>
<div id="login-overlay">
<div class="background"></div>
<div class="wrapper">
<div class="outer">
<div class="inner">
<div class="content">
<i class="fa fa-spinner fa-spin fa-4x"></i>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
@@ -0,0 +1,10 @@
<!-- le CSS -->
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="css/bootstrap-responsive.min.css") }}">
<link rel="stylesheet" href="{{ url_for("static", filename="vendor/font-awesome-4.7.0/css/font-awesome.min.css") }}">
<link rel="stylesheet" href="{{ url_for("plugin.forcelogin.static", filename="css/forcelogin.css") }}">
{% for url in forcelogin_theming %}
<link rel="stylesheet" href="{{ url }}">
{% endfor %}
@@ -0,0 +1,15 @@
<!-- le javascript -->
<script>
var BASE_URL = "{{ url_for('index') }}";
</script>
<script src="{{ url_for("static", filename="js/lib/jquery/jquery.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/sockjs.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/bootstrap/bootstrap.js") }}"></script>
<script src="{{ url_for("static", filename="js/lib/lodash.min.js") }}"></script>
{% assets "js_client" %}
<script type="text/javascript" src="{{ ASSET_URL }}"></script>
{% endassets %}
<script src="{{ url_for("plugin.forcelogin.static", filename="js/main.js") }}"></script>
+3 -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,
@@ -195,6 +195,7 @@ class LoggingPlugin(octoprint.plugin.AssetPlugin,
def get_assets(self):
return dict(js=["js/logging.js"],
clientjs=["clientjs/logging.js"],
less=["less/logging.less"],
css=["css/logging.css"])
Loaded 100 of 267 files, more files were not shown because too many files have changed in this diff. Show more