Compare commits

..
Author SHA1 Message Date
Gina Häußge e603b98d0d 🔖 Preparing release of 1.4.0rc2 2019-12-02 14:11:43 +01:00
Gina Häußge e235fc299f 🐛 Make sure data is set
Closes #3364
2019-12-02 14:07:41 +01:00
Gina Häußge 4f25ed546e 🐛 Only proceed if children is set AND truthy
Closes #3363
2019-12-02 13:55:04 +01:00
Gina Häußge f72b9db6a9 🐛 Fix wrong escape
Closes #3362
2019-12-02 12:24:48 +01:00
Gina Häußge 80e8e33283 🐛 Don't logout always-logged-in AdminUser
If ACL is disabled it doesn't make sense to log it out and it's causing
issues further down the line due to different handling.

Fixes #3361
2019-12-02 12:24:44 +01:00
Gina Häußge 00d0396417 🐛 Fix autologin
Closes #3357
2019-11-29 12:50:16 +01:00
Gina Häußge 59e39662f1 🐛 timelapse: fix accessed event payload field
Closes #3354
2019-11-28 18:02:34 +01:00
Gina Häußge 038e1b9a57 🐛 appkeys: Fix a deprecation warning 2019-11-26 18:42:36 +01:00
Gina Häußge bbefeeeb02 🐛 appkeys: generate string api keys
Instead of binaries.

Closes #3350
2019-11-26 18:35:32 +01:00
Gina Häußge 2801da5c51 💚 Fix unit tests by fixing mocked functions
Closes #3348
2019-11-26 16:22:08 +01:00
Gina Häußge 471dab9406 🐛 Don't try to write None values into upload body
Closes #3349
2019-11-26 15:34:14 +01:00
Gina Häußge 1deb247ce5 🐛 Let functools.wraps do its job
Closes #3348
2019-11-26 15:14:24 +01:00
Gina Häußge 4469a2d84a 🔖 staging/devel is now 1.4.0rc2.dev, devel 1.5.0.dev 2019-11-26 10:36:18 +01:00
Gina Häußge 2da7aa358d 🔖 Preparing release of 1.4.0rc1 2019-11-25 11:57:30 +01:00
Gina Häußge cbb083d7f6 ♻ Do not invalidate / cache on hard reload if printing
Less radical follow-up to #3344 while the kinks for actually needed
UI refreshs are ironed out on that one.
2019-11-25 10:00:03 +01:00
Gina Häußge d68de2c3c7 Revert "Do not refresh on no-cache in request"
This reverts commit 3b1874e
2019-11-25 09:46:50 +01:00
Gina Häußge 454c5e494a Merge pull request #3344 from justfalter/disable-refresh-on-no-cache
Do not refresh on no-cache in request
2019-11-22 12:18:13 +01:00
Mike Ryan 3b1874ea25 Do not refresh on no-cache in request
Remove code that would lead to a refresh upon receiving a
'Cache-Control: no-cache' or 'Pragma: no-cache' in a request. The
purpose of these headers is to invalidate intermdiate proxy caches, not
that of an application server. A refresh in octoprint would lead to
several seconds of high CPU utilization on lower-power systems (like the
Raspberry Pi), leading to stuttering in print jobs.

It is still possible to explicitly cause a refresh by including
`_refresh` in the query parameters of a request.
2019-11-21 08:48:44 -06:00
Gina Häußge e0233dee13 🐛 SWU: Restart after pip update too 2019-11-21 14:27:52 +01:00
Gina Häußge 84a99e1b53 ⬇ Downgrade readthedocs-sphinx-ext
Current versions require jinja2>=2.9 which we can't upgrade to due to
compatibility issues.
2019-11-20 16:02:34 +01:00
Gina Häußge b7e0e89bb4 ⚡️ Precompile markdown & remove changelog
We already have Github's releases with all the changes, we don't need to
keep everything twice.

Instead of the changelog included in the about dialog there's now a link
to the release list, that should suffice.

Implements #3342
2019-11-20 15:35:44 +01:00
Gina Häußge d8c3063813 ⬆️ Update 3rd party deps 2019-11-20 15:30:36 +01:00
Gina Häußge 1485050234 ☔ Add noscript tag
If the user's browser has JS disabled, we should tell them instead of
displaying a non functional UI.

As suggested in https://community.octoprint.org/t/i-forgot-my-octoprint-password-how-can-i-reset-it/215/8?u=foosel
2019-11-15 16:46:06 +01:00
Gina Häußge 6d7721f8f5 ✨ PMGR: More cleanup options
Additional "clean up all leftovers" feature to clean up anything left
over by plugins already uninstalled.

Also takes care of entries in the disabled plugin list now.

See also #3299
2019-11-15 16:28:27 +01:00
Gina Häußge e3ae71eabd 🐛 PMGR: Apparently mtime can sometimes still be None
Handle that.

See https://community.octoprint.org/t/plugins-pip-error-on-fresh-octopi-0-17-0-install/13466
for an example.
2019-11-15 10:43:34 +01:00
Gina Häußge e88041c59e 🐛 PMGR: Remove access attempts on removed field 2019-11-15 10:43:34 +01:00
Gina Häußge e17db4e1cf 📝 SWU: document new pypi_release check type 2019-11-15 10:43:34 +01:00
Gina Häußge 766a64c8f6 Merge pull request #3337 from CapnBry/allowbackanal
Setting to allow gcode analysis to continue during printing
2019-11-12 17:24:14 +01:00
Bryan Mayland 8485d2c9a7 Fix tests failing due to no Settings 2019-11-12 16:07:57 +00:00
Bryan Mayland 397e691a6a Update setting caption for analyzeGcode.runAt 2019-11-12 15:53:06 +00:00
Bryan Mayland 6481f7cf6b webui setting for gcodeAnalysis.runAt 2019-11-12 15:47:54 +00:00
Bryan Mayland 46c527d24a Switch setting to fully control background gcode analysis queueing 2019-11-12 15:28:41 +00:00
Gina Häußge 5392f39cc4 Merge branch 'pr/3335' into devel 2019-11-12 15:28:47 +01:00
Bryan Mayland 4a324b4f5e Setting to allow gcode analysis to continue during printing 2019-11-12 13:49:54 +00:00
Kelly Anderson 2855b0e7a7 Add cbxbiker61 to AUTHORS.md 2019-11-09 00:59:38 -07:00
Kelly Anderson 39e4cd3136 fix another dictionary changed size during iteration exception, possibly triggered only under python3 2019-11-09 00:54:41 -07:00
Gina Häußge 8fefa63c8c 🐛 Fix whitespace issue 2019-11-08 15:15:20 +01:00
Gina Häußge 10532b9118 🐛 SWU: Fix doctest 2019-11-08 14:55:31 +01:00
Gina Häußge 7f2eb470e4 Merge branch 'maintenance' into devel 2019-11-08 14:52:20 +01:00
Gina Häußge 8955b8e0b6 🐛 Fix a unicode bug 2019-11-08 14:48:45 +01:00
Gina Häußge ee9d5048e2 ✨ SWU: Optional pip auto update
Since we can't guarantee for compatibility with future versions of pip
we'll stick to the updater for that being opt-in.
2019-11-08 14:48:29 +01:00
Gina Häußge 09bb74b6c6 ✨ SWU: New check type pypi_release 2019-11-08 14:45:51 +01:00
Gina Häußge 493dddf66e 🐛 to_bytes/to_unicode should pass through None 2019-11-08 14:45:17 +01:00
Gina Häußge 8173f8d0c4 🐛 gcode viewer: Fix swapped G2/G3
Closes #3334
2019-11-08 09:40:09 +01:00
Gina Häußge 01feec47d7 Merge pull request #3330 from dforsi/fix-typos
Fix typos
2019-11-07 12:40:38 +01:00
Daniele Forsi 2b60dbc7e1 Fix typos
Those typos were found with codespell which is available from
https://github.com/lucasdemarchi/codespell.git
2019-11-07 00:02:05 +01:00
Gina Häußge 32f5f36e5a Merge pull request #3328 from balassy/fix/backup-plugin-typo
Fixed a doc typo in the restore command name of the Backup plugin
2019-11-06 19:55:12 +01:00
György Balássy 96294df710 Fixed a typo in the restore command name of the Backup plugin 2019-11-05 22:25:25 +01:00
Gina Häußge ef54cbb148 ☔ Set close_exec flag on serial handle
Possible fix for #3212
2019-11-05 15:41:51 +01:00
Gina Häußge 9cd597a467 🐛 Fix invalid use of 401 response code
Leftovers from fixing #2297.

Fixes #3327
2019-11-05 13:21:49 +01:00
Gina Häußge 2263ebde72 🐛 Fixed ok tracking
Repositioning of clear_to_send clearing removes synchronization issues.

Big thanks to @KevinOConnor for pointing this out!
2019-11-05 12:38:02 +01:00
Gina Häußge 1fd8d597ab Merge pull request #3326 from DominikPalo/feature/support-android-theme-color
Automatically set the toolbar color on Android
2019-11-05 10:57:28 +01:00
Gina Häußge 2aec0b3a75 Merge pull request #3325 from DominikPalo/feature/polish-mac-os-docs
Polish the documentation for macOS (PyCharm setup, macOS naming)
2019-11-05 09:48:47 +01:00
Dominik Palo 47d10a6d3e Set the toolbar color on Android 2019-11-03 11:24:50 +01:00
Dominik Palo ee216ddc93 Merge remote-tracking branch 'upstream/devel' into devel 2019-11-03 09:33:23 +01:00
Dominik Palo 7756d312e2 Update AUTHORS.md 2019-11-03 09:24:51 +01:00
Dominik Palo 19e03eeeb2 Revert a line break 2019-11-03 09:24:51 +01:00
Dominik Palo e73aeba03b Unify macOS naming across docs 2019-11-03 09:23:04 +01:00
Dominik Palo 87f3c5acce Fix documentation for venv step on macOS 2019-11-03 09:19:24 +01:00
Dominik Palo a38a3e67c9 Merge pull request #1 from foosel/maintenance
Maintenance
2019-11-03 09:11:54 +01:00
Gina Häußge 547ae9e13e ♻ SWU: Do not persist check providers
There really is no reason for that
2019-11-01 13:04:20 +01:00
Gina Häußge b031092f07 ✨ PMGR: plugin data cleanup functions
Plugin data can now be cleaned up

  * on a plugin's uninstall through the plugin manager
  * manually through a new action button in the plugin manager

Implements #3299

Ideas for further improvement:

  * Management interface to show "orphaned" plugin data and delete
    on request.
2019-11-01 13:03:47 +01:00
Gina Häußge 6e6dd2c34e 🐛 port can be None 2019-10-31 17:09:49 +01:00
Gina Häußge 759f4f8ea2 🐛 Default checkbox should always be enabled
See #3302
2019-10-31 12:07:31 +01:00
Gina Häußge bee82bcde9 🐛 Treat port=None as port=AUTO on autoconnect
Potential fix for #3267
2019-10-31 11:09:54 +01:00
Gina Häußge 888fb97e66 💡 Clarify Error event in docs
Closes #3210
2019-10-31 09:57:57 +01:00
Gina Häußge 9c775bd899 🐛 Fix overzealous filtering of history entries
Closes #3309
2019-10-30 18:28:53 +01:00
Gina Häußge 4bf3445eef 💡 Fix a doc bug
Closes #3233
2019-10-30 18:23:57 +01:00
Gina Häußge 47b3f51a3f ♻ Speed up the analyser a bit
Closes #3318

Thanks at @jmfrank63 for the heads-up!
2019-10-30 18:10:52 +01:00
Gina Häußge 2e6b85990d 💚 Fix tests 2019-10-30 17:40:49 +01:00
Gina Häußge 30a4b9e9ab Merge branch 'maintenance' into devel
# Conflicts:
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/plugins/virtual_printer/virtual.py
2019-10-30 15:59:30 +01:00
Gina Häußge 81a259e51b ☔ virtual printer: parameter existence checks
Closes #3319
2019-10-30 15:45:36 +01:00
Gina Häußge e85e9661e0 🤷‍♀️ PMGR/SWU: Flag to ignore throttle state
Will allow people to circumvent the
shoot-yourself-in-the-foot-countermeasures by editing config.yaml.

If they do that and stuff then fails due to platform instability it's
their problem.
2019-10-30 15:43:52 +01:00
Gina Häußge 1d60250942 🐛 Only detect sd printing on byte pos change
Should fix #3301, or at least make it way less likely to happen.

The problem seems to have been made worse by `M25` not being blocking
on Klipper and thus the SD printing not being guaranteed to have stopped
yet after its return, meaning the following `M26 S0` will be denied,
causing the file position to not be properly reset and hence the issue
to arise in the first place.
2019-10-30 12:47:40 +01:00
Gina Häußge e11463f6ce ♻ Remove stuff deprecated with 1.4.0
See #1852
2019-10-29 13:12:28 +01:00
Gina Häußge 1146a1bb6f ✨ New events UserLogged(In|Out) & modified ClientOpened
On the push socket only available for admin users.

ClientOpened now also get the remoteAddress stripped from the payload
for guests on the push socket.

Implements #783
2019-10-29 12:39:45 +01:00
Gina Häußge 311fdd5aca 🚸 No connection requirement for timelapse config
No, this doesn't mean that you can start timelapses manually or
anything, only that you do not need to be connected to a printer in
order to change the default timelapse configuration.
2019-10-28 18:13:53 +01:00
Gina Häußge 6ddc55bf80 🚸 Fix timelapse progress bar for missing progress
Closes #2713
2019-10-28 18:10:44 +01:00
Gina Häußge 2c930ef069 🚸 allow wrapping on buttons in selection dialogs
Implements #3292
2019-10-25 15:47:18 +02:00
Gina Häußge 3739bbc652 💄 pmgr/swu: dynamic size for scrollables 2019-10-25 14:26:46 +02:00
Gina Häußge 8d544e63f4 ✨ pmgr: more plugin filters
Implements #3288
2019-10-25 14:18:04 +02:00
Gina Häußge 7e4cf6c5dc ✏️ Fix a help text
Closes #3311
2019-10-25 12:56:31 +02:00
Gina Häußge c8d162c999 ✏️ Clarify use of printer profile fields 2019-10-25 11:46:56 +02:00
Gina Häußge 017515dcc1 🚸 Display errors during loading
Also allow disabling loading screen.

Implements #3298
2019-10-24 17:14:33 +02:00
Gina Häußge d8bd684f96 Merge branch 'maintenance' into devel 2019-10-23 14:04:09 +02:00
Gina Häußge aad5c70eb0 🐛 Fix an escaping bug 2019-10-23 14:01:35 +02:00
Gina Häußge ea2f0a9b17 ♻ Minor refactoring & cleanup 2019-10-23 13:39:03 +02:00
Gina Häußge c4131d5e4b 🐛 Fix anonymous users on tornado endpoints
Closes #2779
2019-10-23 13:38:46 +02:00
Gina Häußge 21127bcf2a Merge branch 'maintenance' into devel 2019-10-23 12:30:06 +02:00
Gina Häußge 04da8afb07 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-10-23 12:00:30 +02:00
Gina Häußge c38f06cce2 Merge branch 'staging/maintenance' into maintenance 2019-10-23 11:48:57 +02:00
Gina Häußge 968f952f69 Merge branch 'rc/maintenance' into staging/maintenance 2019-10-22 12:13:00 +02:00
Gina Häußge 8409fdaa48 Merge branch 'rc/maintenance' 2019-10-21 12:27:16 +02:00
Gina Häußge f29e736427 🔖 Preparing release of 1.3.12 2019-10-21 12:26:04 +02:00
Gina Häußge ac3b6f6df8 🐛 Fix broken sv helper 2019-10-14 17:56:45 +02:00
Gina Häußge a4444ccb68 Merge pull request #3305 from RyuzakiKK/fix/systemd_doc
Fix systemd service documentation path
2019-10-14 16:23:51 +02:00
Ludovico de Nittis 270a0dcb1f Fix systemd service documentation path
The previously suggested `service` folder is not available in a canonical
systemd installation. Instead new services should be placed in
`/etc/systemd/system/`
2019-10-11 22:41:58 +02:00
Gina Häußge a889bec4d8 🐛 Solve sorted issues under Python 3.x
sorted does no longer support sorting None values under Python 3. This
patch introduces a utility function that ensures that None values are
replaced by a configurable default value ("" by default) and utilizes
it in places where sorted gets called with a custom sorting key that
can potentially consist of None values.

Closes #3300
2019-10-10 14:54:07 +02:00
Gina Häußge 7ee9bc32eb ☔ Aggressive escaping 2019-10-09 15:51:38 +02:00
Gina Häußge fd62c1fa3d ☔ Set some more headers, remove CDN URL & remove unused JSESSIONID
* Set X-Content-Type-Options to nosniff
  * Set X-Frame-Options to sameorigin (if not configured otherwise)
  * SockJS iframe fallback no longer embeds sockjs library from a CDN
  * SockJS no longer rewrites the unused JSESSIONID cookie
2019-10-08 16:41:42 +02:00
Gina Häußge a445cfe65e Merge pull request #3297 from mkobler/fix-typo
Fix minor typos
2019-10-08 11:21:17 +02:00
Gina Häußge e20a9925dd Merge pull request #3287 from FHeilmann/patch-2
ActionPrompts: More flexibility for selection_command
2019-10-08 11:20:54 +02:00
Gina Häußge 09a4fb2515 🐛 Fix merge error & add escaping
Closes #3296
2019-10-06 18:52:15 +02:00
Gina Häußge cce7389a42 ✨ SWU: More configuration options
Allow to select github_commit tracking, branch and pip target via UI.

Closes #3295
2019-10-06 18:32:19 +02:00
Gina Häußge b138ea7a47 🐛 SWU: Fix OctoPrint version reporting
See #3295
2019-10-06 16:46:34 +02:00
Gina Häußge 3b708ce079 🔗 Fix a link
As mentioned in #3295
2019-10-06 16:45:13 +02:00
Gina Häußge 4441618be5 🐛 Fix a concurrent modification issue 2019-10-06 16:29:37 +02:00
Mike Kobler 0525c9ab40 Fix minor typos 2019-10-05 18:55:15 -05:00
Gina Häußge 0035e7c3ff 🐛 Fix a merge error 2019-10-02 22:34:39 +02:00
Gina Häußge 073060d253 ✨ PMGR: Search box
Implements #3288
2019-09-26 20:26:47 +02:00
Florian Heilmann 55980a1c2c Update AUTHORS.md 2019-09-25 22:12:51 +02:00
Florian Heilmann 852a2cf157 Fix indentation 2019-09-25 22:11:11 +02:00
Florian Heilmann 2e6ee57162 ActionPrompts: More flexibility for selection_command
Allow users to control how and where the choice is inserted into the response by explicitly including "{choice}" in the selection_command
2019-09-25 22:09:20 +02:00
Gina Häußge 5c54f16ece 🐛 Don't trigger pause on SD cancel
Trying to trigger pausing due to the M25 on an SD cancel could lead
to a dead lock, see #3125
2019-09-25 12:05:03 +02:00
Gina Häußge 04a13268ad 🚸 PMGR: Filter for plugin list
We can now filter all/bundled/3rdparty. Should improve overview.
2019-09-24 11:07:45 +02:00
Gina Häußge 49fdac7528 Merge branch 'maintenance' into devel 2019-09-23 15:26:18 +02:00
Gina Häußge 75f6ef4bae Merge branch 'staging/maintenance' into maintenance
# Conflicts:
#	.versioneer-lookup
2019-09-23 15:25:54 +02:00
Gina Häußge 9fd608691b 🔖 staging is now 1.3.12rc4.dev 2019-09-23 15:24:55 +02:00
Gina Häußge a70a45f062 Merge branch 'staging/maintenance' into rc/maintenance 2019-09-23 12:59:49 +02:00
Gina Häußge 61b0845f19 🔖 Preparing release of 1.3.12rc3 2019-09-23 12:55:39 +02:00
Gina Häußge 30d618267f ☔ Protect against broken language packs 2019-09-20 13:20:46 +02:00
Gina Häußge b9665a8af4 🐛 Don't try to trigger M112 on connection errors
Doesn't make sense, we don't HAVE a connection yet.
2019-09-19 10:19:19 +02:00
Gina Häußge 204d212323 Merge branch 'maintenance' of github.com:foosel/OctoPrint into maintenance 2019-09-18 14:28:15 +02:00
Gina Häußge 04528a635b 🐛 PMGR: Disable plugin mgmt while printer is busy
Not just when only actively printing.

Closes #3278
2019-09-18 14:27:10 +02:00
Gina Häußge 15522a98b0 🐛 GCODE viewer: get rid of deep clone
Fixes #3277
2019-09-18 13:45:01 +02:00
Gina Häußge db1c18075f ☔ Some more escaping 2019-09-17 17:38:55 +02:00
Gina Häußge 3b556e9d79 Merge branch 'maintenance' into devel 2019-09-17 17:34:34 +02:00
Gina Häußge 8761273636 Merge branch 'staging/maintenance' into maintenance 2019-09-17 17:22:10 +02:00
Gina Häußge 08efe80304 🔖 staging/maintenance is now 1.3.12rc3.dev 2019-09-17 17:21:45 +02:00
Gina Häußge c4258c5bb0 🔖 Preparing release of 1.3.12rc2, part 2 2019-09-17 16:20:44 +02:00
Gina Häußge 58799888b7 🐛 SWU: Fix wrong version check
Fixes #3273
2019-09-17 16:18:07 +02:00
Gina Häußge fb6d57963b 🔖 Preparing release of 1.3.12rc2 2019-09-17 14:19:32 +02:00
Gina Häußge 03f228c0ef ☔ Extend safemode to language packs
Cherry-picked from cc1d88c

Implements #3271
2019-09-16 14:35:04 +02:00
Gina Häußge 93ae368f58 🐛 Escape single/double quotes in l10n strings
Cherry-picked from 72eef3e

Closes #3270
2019-09-16 14:34:21 +02:00
Gina Häußge 378752e155 🐛 GCODE viewer: Fix out-of-sync & slider issue, part 2
Now with all files...

Fixes #3272
2019-09-16 14:32:08 +02:00
Gina Häußge bec307900d 🐛 GCODE viewer: Fix out-of-sync & slider issue
Fixes #3272
2019-09-16 14:27:30 +02:00
Gina Häußge cc1d88c4c8 ☔ Extend safemode to language packs
Implements #3271
2019-09-13 16:04:32 +02:00
Gina Häußge 72eef3e224 🐛 Escape single/double quotes in l10n strings
Closes #3270
2019-09-13 15:42:59 +02:00
Gina Häußge 84f6833597 🚨 Fix unused variable issue 2019-09-12 21:05:00 +02:00
Gina Häußge 2a94abdc49 Merge remote-tracking branch 'origin/devel' into devel 2019-09-12 20:51:06 +02:00
Gina Häußge fab5f34aaa 🔀 Rebuilt CSS 2019-09-12 20:50:46 +02:00
Gina Häußge 76f79e5380 🔀 Migrate forcelogin changes to built-in login 2019-09-12 19:20:55 +02:00
Gina Häußge 1b25029207 🔀 Migrate user CLI to new access control 2019-09-12 17:44:33 +02:00
Gina Häußge 8df2a5436b Merge branch 'maintenance' into devel
# Conflicts:
#	setup.py
#	src/octoprint/filemanager/__init__.py
#	src/octoprint/plugins/action_command_prompt/static/js/action_command_prompt.js
#	src/octoprint/plugins/forcelogin/__init__.py
#	src/octoprint/plugins/forcelogin/templates/forcelogin_index.jinja2
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/pluginmanager/static/css/pluginmanager.css
#	src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js
#	src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js
#	src/octoprint/plugins/tracking/__init__.py
#	src/octoprint/printer/standard.py
#	src/octoprint/server/views.py
#	src/octoprint/static/js/app/viewmodels/printerstate.js
#	src/octoprint/static/js/app/viewmodels/users.js
#	src/octoprint/timelapse.py
#	src/octoprint/users.py
#	src/octoprint/util/comm.py
2019-09-12 09:30:28 +02:00
Gina Häußge 72f005b7fe 🔖 maintenance is now 1.3.13.dev 2019-09-10 16:55:06 +02:00
Gina Häußge 0eac10d5a6 🔖 staging/maintenance is now 1.3.12rc2.dev 2019-09-10 16:54:20 +02:00
Gina Häußge 2a42f02aec ⬆️ Require newer environment for future upgrades
This is the last version that supports stock OctoPi 0.14, catering
towards the ancient setuptools and pip versions found on it becomes
more and more unjustifiable overhead.
2019-09-10 13:45:18 +02:00
Gina Häußge 7c48cfd0f7 🔖 Preparing 1.3.12rc1 2019-09-09 18:00:13 +02:00
Gina Häußge bba796d551 ☔ errortracking: filter specific callbacks
We don't want to get swamped by third party plugin error messages on
sentry as that costs money.

Blacklist astroprint messages since they caused issues in the past.
2019-09-09 13:51:54 +02:00
Gina Häußge a855f3e62c ☔ Add fqcn of callbacks to exception loggers
Will allow us to filter for them.
2019-09-09 13:45:22 +02:00
Gina Häußge 5079e7e891 🐛 Clear user management dialogs on close 2019-09-09 12:54:03 +02:00
Gina Häußge ddc948fa94 🔖 errortracking: new DSNs for 1.3.12rc1 2019-09-06 17:09:11 +02:00
Gina Häußge f88f2b25ea 🐛 tracking: Only track plugins in pong event 2019-09-06 16:55:27 +02:00
Gina Häußge ea59dab7ab ✨ Optional print start confirmation
Implements #3250
2019-09-05 14:51:51 +02:00
Gina Häußge f0914c2214 🐛 appkeys: empty user_id = unset user_id
Also some more debug logging

Closes #3257
2019-09-05 14:40:40 +02:00
Gina Häußge b3e76c3ecc 🐛 plugin.version can be None, episode 2 2019-09-05 14:25:17 +02:00
Gina Häußge a4d5acb0b8 Merge pull request #3263 from gdombiak/printer_profiles_add_del_events
All printer profile events are now triggered
2019-09-05 09:34:12 +02:00
Gaston Dombiak 79b66f17b6 Events PRINTER_PROFILE_ADDED and PRINTER_PROFILE_DELETED are now triggered 2019-09-04 22:57:17 -07:00
Gina Häußge bcb6c7a1d4 Create SECURITY.md 2019-09-04 18:03:02 +02:00
Gina Häußge 36198c684f 🐛 Fix scoping issue
Closes #3247
2019-09-04 16:22:31 +02:00
Gina Häußge a3a60c5967 ☔ appkeys: better handling of empty request body 2019-09-04 10:59:03 +02:00
Gina Häußge 6df3cb5c12 🐛 plugin.version may be None 2019-09-04 10:33:42 +02:00
Gina Häußge 0611329a6d Merge pull request #3256 from byarmis/fix/byarmis/3253
Resolve error detecting Python version
2019-09-04 10:01:43 +02:00
Gina Häußge 2f90fca5ce Merge pull request #3249 from gdombiak/printer_profile_events
Printer profile events
2019-09-04 09:51:01 +02:00
Ben Yarmis e4e97190da Resolving issue #3253
Added myself to the AUTHORS.md file
2019-08-25 01:48:11 -05:00
Gaston Dombiak 9c748a85b4 removed ' to march master 2019-08-12 20:40:17 -07:00
Gaston Dombiak 78c2199d89 Fire PRINTER_PROFILE_MODIFIED when printer profile was modified 2019-08-12 20:32:42 -07:00
Gina Häußge 0e67906d1e ♻ tracking: Send plugin list only once per day 2019-07-29 17:38:18 +02:00
Gina Häußge 4c602cba2e ☔ Further hardening against corrupt recovery data 2019-07-29 16:55:32 +02:00
Gina Häußge 89255e2ec9 ☔ Harden against corrupt recovery data
Closes #3199
2019-07-29 16:52:05 +02:00
Gina Häußge 372b3662e9 📝 Add docs for printTimeLeftOrigin field
Closes #3203
2019-07-29 16:37:52 +02:00
Gina Häußge e007dbaf4c 🐛 Fix file selection not being cleared on disconnect
Closes #3224
2019-07-29 13:27:08 +02:00
Gina Häußge dbe07af426 Merge pull request #3202 from cbxbiker61/devel
fix RuntimeError: dictionary changed size during iteration
2019-07-25 10:17:45 +02:00
Gina Häußge f67f9b9399 🐛 Fix --admin flag on add command 2019-07-22 15:06:09 +02:00
Gina Häußge c6c5328418 ✨ Add list/activate/deactivate commands 2019-07-22 15:05:51 +02:00
Gina Häußge accbfc2b45 🐛 Fix settings passing 2019-07-22 15:04:27 +02:00
Gina Häußge 9976f2b7a3 🐛 Fix a broken import 2019-07-22 14:00:54 +02:00
Gina Häußge f249563b2c 🐛 At least use configured user manager class
Making the plugin hook work would be a ton of overhead due to the
components dictionary that needs to be supplied to it for user manager
initialization, however at the very least we should support
configuration of the used user manager class.

Both features are rarely used if at all, but we should be aware of this.

Also changed some wording, fixed to unicode and removed redundancy from
the sub commands (e.g. just "add" instead of "add_user") and flags.
2019-07-22 14:00:43 +02:00
Aliaksei Pilko 09e023917c Amend settings ref 2019-07-19 18:08:31 +01:00
Aliaksei Pilko 799b86b287 Update copyright 2019-07-18 15:41:32 +01:00
Aliaksei Pilko ea1bcf8e5d Add user accounts cli
Add forgot password link at login

Update AUTHORS.md
2019-07-17 19:54:21 +01:00
Piotr Usewicz ee93e25ffd Rename currentLine to current_line 2019-07-16 11:02:52 +02:00
Gina Häußge d25f664be3 🐛 printer safety: Anycubic 1.1.2 is already safe
Fix off by one error.

See also https://community.octoprint.org/t/octoprint-tells-me-that-my-printers-firmware-lacks-mandatory-safety-features-what-does-this-mean/350/61
2019-07-16 10:47:42 +02:00
Gina Häußge 3bffe4f7cb Merge pull request #3225 from eyal0/patch-4
Quote arguments in pip install
2019-07-11 11:20:20 +02:00
Eyal f140dd9d44 Quote arguments in pip install
If the argument is not quoted, the shell will interpret the braces.
2019-07-08 21:20:08 -04:00
Gina Häußge d44747b39a 🐛 Fix long_running_command flag for M191
Closes #3220
2019-07-08 11:26:02 +02:00
Gina Häußge f2da9d8d7d Merge pull request #3217 from gdombiak/docs_typo
Fixed typo in chambers documentation
2019-07-05 11:16:24 +02:00
Gaston Dombiak 5483ef7cd4 Fixed typo in chambers documentation 2019-07-04 23:19:35 -07:00
Gina Häußge 85d212ba97 ☔ More resilience against garbage on the line on initial connect
We'll now send the hello command twice, and a third time if we run into
a timeout during initial connect.

Closes #3206
2019-07-02 16:35:57 +02:00
Gina Häußge 44af09580a 🚸 Make clear when GCODE scripts are executed
Closes #3198
2019-07-02 13:56:19 +02:00
Gina Häußge 530fca95e4 ☔ Include wizard flag in etag
Additional protection against #3211 and #3166
2019-07-02 13:48:28 +02:00
Gina Häußge 59ae7e39f2 ☔ Only set relevant cache control headers
We don't want to accidentally overwrite anything again.
2019-07-02 13:43:57 +02:00
Gina Häußge 72167d14d2 🐛 Fix caching headers on / in case of wizards
Revalidation header from ceade46dd7 was
overwriting custom header in case of active wizards, causing the browser
to cache HTML code with enabled wizards.

This fixes this by checking if the headers in question actually need to
be set and aren't already there.
2019-07-02 12:44:29 +02:00
Gina Häußge 2c6568acd1 ✨ Mimetype guessing for the webcam test
Related to #3207
2019-07-01 17:17:34 +02:00
Gina Häußge e27c216a05 Merge branch 'master' into maintenance 2019-06-27 10:19:12 +02:00
Gina Häußge 7b4c148dd7 ✨ tracking: track slicing events
Gives us some numbers the next time someone complains about
slicer support.
2019-06-26 19:27:57 +02:00
Gina Häußge a924520dd6 ✨ tracking: track plugins & versions on startup
Requested feature by plugin developers, will also allow us to compile
stuff like top10 lists.
2019-06-26 18:32:33 +02:00
Kelly Anderson 1c3e463ac6 fix RuntimeError: dictionary changed size during iteration 2019-06-22 18:11:36 -06:00
Gina Häußge e88eb6dd85 ☔ PMGR: Prevent installs while throttled 2019-06-19 15:48:18 +02:00
Gina Häußge 59dfa994bd ☔ SWU: Prevent updates while throttled 2019-06-19 15:41:11 +02:00
Gina Häußge 6959ce4d38 💚 Try to fix doc build by pinning a dep, 2nd try 2019-06-19 11:52:06 +02:00
Gina Häußge 08bc0082cf 💚 Try to fix doc build by pinning a dep 2019-06-19 11:46:53 +02:00
Gina Häußge 6069d74a54 💚 Fix unit tests 2019-06-18 13:35:21 +02:00
Gina Häußge 68ee7030f1 ☔ Send M112 on disconnect due to error (configurable)
Try to disable heaters and such. Might fail, but worth a try at least.
Only do that if we are not SD printing though.
2019-06-17 18:35:44 +02:00
Gina Häußge 81342acccc ☔ Detect endless resend requests & abort
If the printer keeps requesting the same line over and over again,
something is either seriously wrong with the line or with the connection

In any case, log an error and disconnect.
2019-06-17 18:35:44 +02:00
Gina Häußge e029f33901 Merge pull request #3195 from dmweis/patch-2
Fix typo
2019-06-11 10:41:33 +02:00
David Weis 7bd8cff137 Fix typo 2019-06-08 14:14:58 +01:00
Gina Häußge 055dcfa0e1 Merge pull request #3192 from dovecode/translatable-string-fixes
Various translatable text fixes and fixed plugin install message during restore
2019-06-05 13:32:10 +02:00
Nicolai Nielsen 8acf417383 Removed extra curly brace in plugin install message during restore
Fixed plugin install message for UI (never worked!)
Fixed grammar in connectivity initial setup
Added space at end of lines for several multiline messages
2019-06-04 11:47:41 -05:00
Gina Häußge b50e1aee8a 🚨 More consistent whitespace 2019-06-04 15:20:27 +02:00
Gina Häußge c714bce17e Merge pull request #3191 from Flamenco/my_maintenance
Add documentation when target temperature is set to 0
2019-06-04 15:19:23 +02:00
Steven Spungin a9a8e48489 Add new author 2019-06-04 09:00:35 -04:00
Steven Spungin 9dec840818 Add documentation when target temperature is set to 0 2019-06-04 08:57:10 -04:00
Gina Häußge 9af125ca6d 🚨 Consistent whitespace 2019-06-03 13:25:02 +02:00
Gina Häußge 1f4fabe6ef 🐛 PMGR: Refresh data from server if needed on endpoint GET
Closes #3190
2019-06-03 12:17:03 +02:00
Gina Häußge 121f36704d Merge pull request #3184 from dovecode/action_prompt_warning_missing_space
Add space in disable warning message
2019-05-29 18:13:51 +02:00
Nicolai Nielsen 85ff545c07 Add space in disable warning message 2019-05-29 10:10:52 -05:00
Gina Häußge 3662c84de5 Merge branch 'pr/3183' into maintenance 2019-05-28 16:35:00 +02:00
Gina Häußge 79558fdfbf Merge pull request #3179 from dovecode/uninstall_plugin_confirmation
Added confirmation dialog before uninstalling plugin
2019-05-28 16:21:44 +02:00
Nicolai Nielsen 11040f272a Added confirmation dialog before uninstalling plugin
Added confirmation dialog before disabling plugin
Added configuration options to control the confirmation dialogs
Defaults are not to confirm for disabling but confirm for uninstalling
2019-05-27 19:03:29 -05:00
Janne Mäntyharju fa2716c65c Calculate filament usage for all extruders is M605 duplicate/mirror command is used (Issue #3075) 2019-05-27 22:02:34 +03:00
Gina Häußge 768b06e35a ✨ Allow disabling of closing dialogs by click outside
New setting: Settings > Appearance > Close dialogs by clicking outside

Implements #3162
2019-05-27 16:58:45 +02:00
Gina Häußge 0820c23aea Merge pull request #3180 from AndyQ/clear_term_patch
Added button to terminal window to all log window to be cleared out
2019-05-27 16:26:34 +02:00
Gina Häußge 361fbaa366 🐛 pmgr: Smaller height for plugin list
Should work around #3161
2019-05-27 16:22:50 +02:00
Gina Häußge a91359f2af 🚸 Change icon & wording 2019-05-27 16:21:03 +02:00
AndyQ 4bfabf82ae Fixed typo and changed link to clearAllLogs
Both logs (fancy and plain) cleared out at same time
2019-05-27 15:01:14 +01:00
Gina Häußge c90f556fe9 📝 github meta: Clarify devel vs maintenance base 2019-05-27 11:14:31 +02:00
AndyQ 352b190a72 Added button to terminal window to all log window to be cleared out 2019-05-26 12:49:03 +01:00
Gina Häußge e9b0bd9e65 Create FUNDING.yml 2019-05-23 13:08:50 +02:00
Gina Häußge c8ea808d93 🚸 Include seconds in upload date
See #3174
2019-05-21 15:18:24 +02:00
Gina Häußge d40c3e6241 🚸 Add upload date to selected file information
Should make it more clear when an update due to a new upload happens.

Closes #3174
2019-05-21 15:05:28 +02:00
Gina Häußge e94f789b72 🐛 Always report all tools in sharedNozzle setups
Fixes #3177

See also https://community.octoprint.org/t/9620/4
2019-05-21 14:29:15 +02:00
Gina Häußge 9ff44c49a6 🐛 Fix broken tool filtering 2019-05-21 14:20:41 +02:00
Gina Häußge c7b933ba00 🐛 forcelogin: Do not touch static endpoints
Closes #3176
2019-05-21 12:07:39 +02:00
Gina Häußge 6765b25803 🚸 action prompt: show icon for dismissed prompts in navbar 2019-05-21 10:37:47 +02:00
Gina Häußge 59b60f5dad 🐛 action prompt: close & delete prompt on disconnect
As mentioned in #3171
2019-05-20 19:55:10 +02:00
Gina Häußge 2822992843 🚸 action prompt: allow to cancel dialogs
Closes #3171
2019-05-20 19:49:06 +02:00
Gina Häußge 1b82aa859f 🐛 Fix accidental test code commit 2019-05-20 16:48:00 +02:00
Gina Häußge 12be637f85 ✨ Add setting for parity double open workaround
Can now be set to be applied if possibly needed (OS is a Debian Linux),
always or never.

Closes #3169, enhances #3167
2019-05-20 16:46:45 +02:00
Kyle Evans 3bd9d11fc3 comm: Don't open twice on FreeBSD
Originally introduced by PR #673 to fix reconnect issues on pyserial,
OctoPrint will first open the serial port with PARITY_ODD then close it
again and reopen with the desired PARITY_NONE. This works around issues
likely sitting somewhere in the linux tty layer, at least on some
distributions, that don't necessarily exist on other platforms.

Stop doing the workaround on FreeBSD to start with, as this is the only
platform I can effectively test. I suspect MacOS/Windows likely also don't
need to do this.
2019-05-17 22:43:13 -05:00
Gina Häußge e864d6b03e 🚸 Ensure line breaks on copy of terminal contents 2019-05-15 17:35:57 +02:00
Gina Häußge 547db7c1f5 ☔ pmgr: better handling of unexpected repository format
Closes #3157 and Sentry SERVER-116
2019-05-15 17:34:54 +02:00
Gina Häußge d6516e4a4c 🐛 tracking: handle time==None case
Closes #3156 and Sentry SERVER-WR
2019-05-15 15:19:57 +02:00
Gina Häußge 2387b4a771 🐛 backup: make sure exclude is always a list
Closes #3155 and Sentry SERVER-119
2019-05-15 15:15:25 +02:00
Gina Häußge b03d43156d 🐛 Strip interface tags from addresses on local check
Closes #3143 and Sentry SERVER-11B
2019-05-15 13:19:14 +02:00
Gina Häußge 07423712a6 🐛 Fix wrong variable name in exception handler
Closes #3153 & Sentry SERVER-11A
2019-05-15 11:48:45 +02:00
Gina Häußge 81735d07c9 Merge branch 'rc/maintenance' 2019-05-13 14:54:51 +02:00
Gina Häußge 03e328fd13 📝 Fix a documentation issue
Fixes #3117
2019-04-10 17:13:29 +02:00
Gina Häußge 7efcf00baf Merge pull request #3106 from hlovdal/explicit_python_version
README: Use explicit python version for virtualenv
2019-04-05 09:47:52 +02:00
Håkon Løvdal a3254466f7 Whitespace fixes 2019-04-05 01:10:30 +02:00
Håkon Løvdal f8dc504773 Add example of using explicit python version 2019-04-05 01:10:30 +02:00
237 changed files with 9505 additions and 14610 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# These are supported funding model platforms
github: [foosel]
patreon: foosel
custom: https://octoprint.org/support-octoprint/
+3 -2
View File
@@ -16,8 +16,9 @@ checklist:
made sure your changes don't interfere with current development by
talking it through with the maintainers, e.g. through a
Brainstorming ticket
* [ ] Your PR targets OctoPrint's devel branch, or maintenance if it's
a bug fix for an issue present in the current stable version (no PRs
* [ ] Your PR targets OctoPrint's devel branch if it's a completely
new feature, or maintenance if it's a bug fix or improvement of
existing functionality for the current stable version (no PRs
against master or anything else please)
* [ ] Your PR was opened from a custom branch on your repository
(no PRs from your version of master, maintenance or devel please),
+12 -9
View File
@@ -18,16 +18,19 @@ prerelease
HEAD
\(detached.*
# maintenance is currently the branch for preparation of maintenance release 1.3.12
# maintenance is currently the branch for preparation of maintenance release 1.3.13
# so are any fix/... and improve/... branches
maintenance 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
fix/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
improve/.* 1.3.12 73df8c2407f04756261acfe62ac3d72877f8a97d pep440-dev
maintenance 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
fix/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
improve/.* 1.3.13 2a42f02aecaedf2c55579984e0bc94e44402cc15 pep440-dev
# staging/maintenance is currently the branch for preparation of 1.3.11rc4
# staging/maintenance is currently the branch for preparation of 1.3.12rc4
# so is regressionfix/...
staging/maintenance 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
regressionfix/.* 1.3.11rc4 af3285854995fb5b910fd2ce869e26c02d57bbc2 pep440-dev
staging/maintenance 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 pep440-dev
regressionfix/.* 1.3.12rc4 a70a45f062687beb510fb3192e4227754e1dff39 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
# staging/devel is currently the branch for preparation of 1.4.0rc2
staging/devel 1.4.0rc2 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
# every other branch is a development branch and thus gets resolved to 1.5.0-dev for now
.* 1.5.0 2da7aa358d950b4567aaab8f18d6b5779193e077 pep440-dev
+10
View File
@@ -105,6 +105,16 @@ date of first contribution):
* [Jack Wilsdon](https://github.com/jackwilsdon)
* [Ryan Finnie](https://github.com/rfinnie)
* [Timur Duehr](https://github.com/tduehr)
* [Nicolai Nielsen](https://github.com/dovecode)
* [Janne Mäntyharju](https://github.com/JanneMantyharju)
* [Steven Spungin](https://github.com/flamenco)
* [Piotr Usewicz](https://github.com/pusewicz)
* [Aliaksei Pilko](https://github.com/aliaksei135)
* [Ben Yarmis](https://github.com/byarmis)
* [Florian Heilmann](https://github.com/FHeilmann)
* [Ludovico de Nittis](https://github.com/RyuzakiKK)
* [Dominik Paľo](https://github.com/DominikPalo)
* [Kelly Anderson](https://github.com/cbxbiker61)
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
+3 -1172
View File
File diff suppressed because it is too large. Load diff
+5 -4
View File
@@ -31,7 +31,7 @@ If you enjoy OctoPrint, please consider becoming a regular supporter!**
You are currently looking at the source code repository of OctoPrint. If you already installed it
(e.g. by using the Raspberry Pi targeted distribution [OctoPi](https://github.com/guysoft/OctoPi)) and only
want to find out how to use it, [the documentation](http://docs.octoprint.org/) and [the public wiki](https://github.com/foosel/OctoPrint/wiki)
might be of more interest for you. You might also want to subscribe to join
might be of more interest for you. You might also want to subscribe to join
[the community forum at community.octoprint.org](https://community.octoprint.org) where there are other active users who might be
able to help you with any questions you might have.
@@ -39,7 +39,7 @@ able to help you with any questions you might have.
Contributions of all kinds are welcome, not only in the form of code but also with regards to the
[official documentation](http://docs.octoprint.org/) or [the public wiki](https://github.com/foosel/OctoPrint/wiki), debugging help
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
in the [bug tracker](https://github.com/foosel/OctoPrint/issues), support of other users on
[the community forum at community.octoprint.org](https://community.octoprint.org)
and also [financially](https://octoprint.org/support-octoprint/?utm_source=github&utm_medium=readme).
@@ -65,14 +65,15 @@ you already have Python 2.7, 3.6 or 3.7, pip and virtualenv set up on your syste
1. Checkout OctoPrint: `git clone https://github.com/foosel/OctoPrint.git`
2. Change into the OctoPrint folder: `cd OctoPrint`
3. Create a user-owned virtual environment therein: `virtualenv venv`
3. Create a user-owned virtual environment therein: `virtualenv venv` if your system default python version is
python 2.7, otherwise you need to specify the version explicitly, e.g. `virtualenv --python=python2.7 venv`.
4. Install OctoPrint *into that virtual environment*: `./venv/bin/pip install .`
You may then start the OctoPrint server via `/path/to/OctoPrint/venv/bin/octoprint`, see [Usage](#usage)
for details.
After installation, please make sure you follow the first-run wizard and set up
access control as necessary.
access control as necessary.
## Dependencies
+11
View File
@@ -0,0 +1,11 @@
# Security Policy
## Supported Versions
Always update to the latest version of OctoPrint to keep up with security patches.
## Reporting a Vulnerability
Email to security@octoprint.org.
For the sake of the userbase of OctoPrint please always disclose responsibly and with a 90+ day window.
+10 -5
View File
@@ -8,8 +8,8 @@ thanks to everyone who contributed!
* Andre Bubel
* Andrew Moorby
* ANTONIO AUGUSTO DE LIMA PONTES
* Arnljot Arntsen
* Bjorn Breckenridge
* Boris Hussein
* Brad Jackson
* Christian Petropolis
@@ -22,36 +22,41 @@ thanks to everyone who contributed!
* Eric Betts
* Ernesto Martinez
* Franziska Kunsmann
* GadgetAngel
* George Robles
* jean-claude migneault
* Jeff Renfer
* Jefferson Hunt
* Jeremiah Avery
* Joseph Payne
* John Robinson (JRo)
* Joshua Wills
* Justin Kaufman
* Kaile Riser
* Kale Stedman
* Kazuhiro Ogura
* Kyle Menigoz
* LA 3D Printer Repair
* Lee Dohm
* LulzBot®
* Makespace Madrid
* Mark Walker
* Martin Majewski
* Michael Aumock
* Miles Flavel
* Mosaic Manufacturing
* OMER MEHMET SUTAS
* Patrick Glyré
* Patrick McGinnis
* Prof Yuh Wen Chen
* Randy C. Will
* Ranjib Dey
* Robert Gusek
* Samer Najia
* Shawn Lewis
* Simon Hallam
* Stefan Krister
* Sven Mueller
* TEVO 3D Printers
* Trent Shumay
* Ulrich Kempken
* Vladislav Kuzemchik
and 1544 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel)!
and 1653 more wonderful people pledging on the [Patreon campaign](https://patreon.com/foosel) or via [Github Sponsors](https://github.com/users/foosel/sponsorship)!
+11
View File
@@ -218,6 +218,17 @@ Progress information
- 1
- Integer
- Estimate of time left to print, in seconds
* - ``printTimeLeftOrigin``
- 1
- String
- Origin of the current time left estimate. Can currently be either of:
* ``linear``: based on an linear approximation of the progress in file in bytes vs time
* ``analysis``: based on an analysis of the file
* ``estimate``: calculated estimate after stabilization of linear estimation
* ``average``: based on the average total from past prints of the same model against the same printer profile
* ``mixed-analysis``: mixture of ``estimate`` and ``analysis``
* ``mixed-average``: mixture of ``estimate`` and ``average``
.. _sec-api-datamodel-files:
+9 -4
View File
@@ -148,8 +148,14 @@ Login
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.
login, whether active or passive. The active (username/password) login may also return a :http:statuscode:`403` in
case of a username/password mismatch, unknown user or a deactivated account.
.. warning::
Previous versions of this API endpoint did return a :http:statuscode:`401` in case of a username/password
mismatch or an unknown user. That was incompatible with basic authentication since it was a wrong use of
the :http:statuscode:`401` code and got therefore changed as part of a bug fix.
: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
@@ -157,8 +163,7 @@ Login
: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
:status 403: Username/password mismatch, unknown user or deactivated account
.. _sec-api-general-logout:
-1
View File
@@ -9,7 +9,6 @@ REST API
general.rst
version.rst
apps.rst
connection.rst
files.rst
job.rst
+5 -5
View File
@@ -350,7 +350,7 @@ Issue a tool command
Sets the given target temperature on the printer's tools. Additional parameters:
* ``targets``: Target temperature(s) to set, properties must match the format ``tool{n}`` with ``n`` being the
tool's index starting with 0.
tool's index starting with 0. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's tools. Additional parameters:
@@ -630,7 +630,7 @@ Issue a bed command
target
Sets the given target temperature on the printer's bed. Additional parameters:
* ``target``: Target temperature to set.
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's bed. Additional parameters:
@@ -770,7 +770,7 @@ Retrieve the current bed state
Issue a chamber command
=======================
.. http:post:: /api/printer/bed
.. http:post:: /api/printer/chamber
Chamber commands allow setting the temperature and temperature offsets for the printer's heated chamber. Available commands
are:
@@ -778,7 +778,7 @@ Issue a chamber command
target
Sets the given target temperature on the printer's chamber. Additional parameters:
* ``target``: Target temperature to set.
* ``target``: Target temperature to set. A value of `0` will turn the heater off.
offset
Sets the given temperature offset on the printer's chamber. Additional parameters:
@@ -790,7 +790,7 @@ Issue a chamber command
Upon success, a status code of :http:statuscode:`204` and an empty body is returned.
If no heated chambed is configured for the currently selected printer profile, the resource will return
If no heated chamber is configured for the currently selected printer profile, the resource will return
an :http:statuscode:`409`.
Requires user rights.
+1 -1
View File
@@ -27,7 +27,7 @@ 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``.
It adds two new commands, ``backup:backup`` and ``backup:restore``.
.. code-block:: none
+1 -1
View File
@@ -14,7 +14,7 @@ network running Microsoft Windows. You will be able to just double click on the
OctoPrint instance icon in "Networks > Other Devices" in your Windows Explorer,
which will take you directly to the web frontend.
The ZeroConf support allows OctoPrint to announce itself to Safari on MacOS X
The ZeroConf support allows OctoPrint to announce itself to Safari on macOS
on the same network.
Linux users should install `Avahi <http://avahi.org>`_ and can then use one
+4
View File
@@ -196,6 +196,10 @@ Version checks
* ``checkout_folder``: (mandatory) The full path to the folder with a valid git
repository to check.
* ``pypi_release``: Checks `pypi.org <https://pypi.org>`_ for new releases of a specified package.
* ``package``: (mandatory) Name of the package which to check.
* ``command_line``: Uses a provided script to determine whether an update
is available. Additional config parameters:
+5 -3
View File
@@ -5,7 +5,7 @@ config.yaml
If not specified via the command line, the main configuration file ``config.yaml`` for OctoPrint is expected in its
settings folder, which unless defined differently via the command line is located at ``~/.octoprint`` on Linux, at
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on MacOS. If the file is not there,
``%APPDATA%/OctoPrint`` on Windows and at ``~/Library/Application Support/OctoPrint`` on macOS. If the file is not there,
you can just create it - it will only get created by OctoPrint once you save settings that deviate from the default
settings.
@@ -290,6 +290,9 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Whether to delete generated web assets on server startup (forcing a regeneration)
clean_on_startup: true
# enable or disable the loading animation
showLoadingAnimation: true
# Settings for the virtual printer
virtualPrinter:
@@ -425,8 +428,7 @@ The following settings are only relevant to you if you want to do OctoPrint deve
# Lines to send on simulated reset
resetLines:
- start
- Marlin: Virtual Marlin!
- "\x80"
- "Marlin: Virtual Marlin!"
- "SD card ok"
# Initial set of prepared oks to use instead of regular ok (e.g. to simulate
+1 -1
View File
@@ -5,7 +5,7 @@ logging.yaml
The logging configuration file ``logging.yaml`` for OctoPrint is expected in its settings folder, which unless defined
differently on the command line is located at ``~/.octoprint`` on Linux, at ``%APPDATA%/OctoPrint`` on Windows and at
``~/Library/Application Support/OctoPrint`` on MacOS.
``~/Library/Application Support/OctoPrint`` on macOS.
You can use it to change the log levels of the individual components within OctoPrint, which might be necessary to help
in debugging issues you are experiencing, or to change the configuration of the logging handlers themselves, e.g. in
+18 -7
View File
@@ -17,21 +17,30 @@ below.
* `Python 3.7 <https://python.org>`_ including ``pip``, ``setuptools`` and ``virtualenv``
* `Git <https://git-scm.com>`_
* Checkout the OctoPrint sources from their Git repository:
* Checkout the OctoPrint sources from their Git repository:
* ``git clone -b devel https://github.com/foosel/OctoPrint.git``
* Enter the checked out source folder: ``cd OctoPrint``
* Create virtual environments in the checked out source folder for both Python 2.7 and Python 3.7 to use for
installing and running OctoPrint and its dependencies (this avoids potential versioning issues for the dependencies
with system wide installed instances):
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* PY2: ``virtualenv --python=python2 venv2``
* PY3: ``virtualenv --python=python3 venv3``
* Activate one of the virtual environments:
* PY2: ``source venv2/bin/activate`` (Linux, MacOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, MacOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* PY2: ``source venv2/bin/activate`` (Linux, macOS) or ``source venv2/Scripts/activate`` (Git Bash under Windows, see below)
* PY3: ``source venv3/bin/activate`` (Linux, macOS) or ``source venv3/Scripts/activate`` (Git Bash under Windows, see below)
* Update ``pip`` in the virtual environment:
* ``pip install --upgrade pip``
* Install OctoPrint in `"editable" mode <https://pip.pypa.io/en/stable/reference/pip_install/#editable-installs>`_,
including its regular *and* development and plugin development dependencies:
including its regular *and* development and plugin development dependencies:
* ``pip install -e .[develop,plugins]``
When the virtual environment is activated you can then:
@@ -197,8 +206,10 @@ PyCharm
.......
- "File" > "Open ...", select OctoPrint checkout folder (e.g. ``~/devel/OctoPrint`` or ``C:\Devel\OctoPrint``)
- "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
- **(Linux, Windows)** "File" > "Settings ..." > "Project: OctoPrint" > "Project Interpreter" > "Add local ...", select OctoPrint venv
folder (e.g. ``~/devel/OctoPrint/venv`` or ``C:\Devel\OctoPrint\venv``)
- **(macOS)** "PyCharm" > "Preferences ..." > "Project: OctoPrint" > "Project Interpreter" > "Add ..." >
"Virtualenv Environment > "Existing Environment", select OctoPrint venv folder (e.g. ``~/devel/OctoPrint/venv``)
- Right click "src" in project tree, mark as source folder
- Add Run/Debug Configuration, select "Python":
+1 -1
View File
@@ -17,7 +17,7 @@ be found in the full :ref:`config.yaml documentation <sec-configuration-config_y
The steps to take are as follows:
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on MacOS.
* Find config.yaml in the OctoPrint settings folder. Usually in ``~/.octoprint`` on Linux, in ``%APPDATA%/OctoPrint`` on Windows and in ``~/Library/Application Support/OctoPrint`` on macOS.
* Add or extend the ``devel`` section with:
.. code-block:: yaml
+35 -2
View File
@@ -104,7 +104,8 @@ ClientOpened
Payload:
* ``remoteAddress``: the remote address (IP) of the client that connected
* ``remoteAddress``: the remote address (IP) of the client that connected. On the push socket only available with
a valid login session.
**Note:** Name changed in version 1.1.0
@@ -115,6 +116,19 @@ ClientClosed
* ``remoteAddress``: the remote address (IP) of the client that disconnected
UserLoggedIn
A user logged in. On the push socket only available with a valid login session with admin rights.
Payload:
* ``username``: the name of the user who logged in
UserLoggedOut
A user logged out. On the push socket only available with a valid login session with admin rights.
Payload:
* ``username``: the name of the user who logged out
ConnectivityChanged
The server's internet connectivity changed
@@ -151,6 +165,9 @@ Error
An unrecoverable error has been encountered, either as reported by the firmware (e.g. a thermal runaway) or
on the connection.
Note that this event will not fire for error messages from the firmware that are handled (and as such recovered from)
either by OctoPrint or a plugin.
Payload:
* ``error``: the error string
@@ -588,6 +605,7 @@ SlicingStarted
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -599,6 +617,7 @@ SlicingDone
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -611,6 +630,7 @@ SlicingCancelled
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -621,6 +641,7 @@ SlicingFailed
Payload:
* ``slicer``: the used slicer
* ``stl``: the STL's filename
* ``stl_location``: the STL's location
* ``gcode``: the sliced GCODE's filename
@@ -636,7 +657,7 @@ SlicingProfileAdded
* ``profile``: the profile that was added
SlicingProfileModified
A new slicing profile was modified.
A slicing profile was modified.
Payload:
@@ -661,3 +682,15 @@ SettingsUpdated
This event may also be triggered if calling code of :py:class:`octoprint.settings.Settings.save` or
:py:class:`octoprint.plugin.PluginSettings.save` sets the ``trigger_event`` parameter to ``True``.
.. _sec-events-available_events-printer_profile:
Printer Profile
---------------
PrinterProfileModified
A printer profile was modified.
Payload:
* ``identifier``: the identifier of the modified printer profile
+1 -1
View File
@@ -11,7 +11,7 @@ is clicked.
Unless :ref:`configured otherwise <sec-configuration-config_yaml-folder>`, OctoPrint expects scripts to be located in
the ``scripts/gcode`` folder in OctoPrint configuration directory (per default ``~/.octoprint`` on Linux, ``%APPDATA%\OctoPrint``
on Windows and ``~/Library/Application Support/OctoPrint`` on MacOS).
on Windows and ``~/Library/Application Support/OctoPrint`` on macOS).
These GCODE scripts are backed by the templating engine Jinja2, allowing more than just
simple "send-as-is" scripts but making use of a full blown templating language in order to create your scripts. To
+17 -10
View File
@@ -5,19 +5,20 @@ Safe mode
*********
With the advent of support for plugins in OctoPrint, it quickly became apparent that some of the bugs
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins instead of
OctoPrint itself.
reported on OctoPrint's bug tracker were actually bugs with installed third party plugins or language
packs instead of OctoPrint itself.
To allow an easier identification of these cases, OctoPrint 1.3.0 introduced safe mode. Starting
OctoPrint in safe mode disables all plugins that are not bundled with OctoPrint, allowing to easier
identify most cases where a third party plugin is the culprit of an observed issue.
OctoPrint in safe mode disables all plugins (and starting with 1.3.13 also all language packs) that are
not bundled with OctoPrint, allowing to easier identify most cases where a third party plugin or language
pack is the culprit of an observed issue.
Additionally, OctoPrint allows uninstalling plugins in this mode, allowing recovery from cases where
a third party plugin causes the server to not start up or the web interface to not render or function
correctly anymore.
Additionally, OctoPrint allows uninstalling plugins and language packs in this mode, allowing recovery
from cases where a third party addition causes the server to not start up or the web interface to not
render or function correctly anymore.
Whenever reporting an issue with OctoPrint, please always attempt to reproduce it in safe mode as well to
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party plugins.
ensure it really is an issue in OctoPrint itself and now caused by one of your installed third party additions.
.. _sec-features-safemode-how:
@@ -73,11 +74,17 @@ When OctoPrint is running in safe mode the following changes to its normal opera
* OctoPrint will not enable any of the installed third party plugins. OctoPrint considers all plugins third
party plugins that do not ship with OctoPrint's sources, so any plugins installed either via `pip` or
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint`` (Windows) and
``~/Library/Application Support/OctoPrint`` (MacOS).
into OctoPrint's plugin folder at ``~/.octoprint/plugins`` (Linux), ``%APPDATA%/OctoPrint/plugins`` (Windows) and
``~/Library/Application Support/OctoPrint/plugins`` (macOS).
* OctoPrint will not enable any of the installed third party language packs. OctoPrint considers all language packs
third party language packs that do not ship with OctoPrint's sources, so any language plugins installed
through the language pack manager within settings and/or stored in the language pack folder at
``~/.octoprint/translations`` (Linux), ``%APPDATA%/OctoPrint/translations`` (Windows) or
``~/Library/Application Support/OctoPrint/translations`` (macOS).
* OctoPrint will still allow to uninstall third party plugins through the built-in Plugin Manager.
* OctoPrint will still allow to disable (bundled) plugins that are still enabled.
* OctoPrint will not allow to enable third party plugins.
* OctoPrint will still allow to manage language packs.
* OctoPrint's web interface will display a notification to remind you that it is running in
safe mode.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 38 KiB

After

Width:  |  Height:  |  Size: 58 KiB

+1 -1
View File
@@ -42,7 +42,7 @@
To register for all message types, provide ``*`` as the type to register for.
``handler`` is expected to be a function accepting one object parameter ``eventObj``, consisting
of the received message as property ``key`` and the received payload (if any) as property ``data``.
of the received message as property ``event`` and the received payload (if any) as property ``data``.
.. code-block:: javascript
+1 -1
View File
@@ -166,7 +166,7 @@ Now, the execution order of the ``on_after_startup`` method will be determined b
This will result in the following messages to be generated:
.. code-block:: plain
.. code-block:: none
Plugin B starting up
Plugin C starting up
+5 -6
View File
@@ -11,7 +11,7 @@ import requests
from contextlib import closing
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, set_source_info, parselinenos, logger, container_wrapper
nodes, parselinenos, logger, container_wrapper
if False:
# For type annotation
@@ -39,11 +39,10 @@ class OnlineIncludeReader(LiteralIncludeReader):
return lines
except (IOError, OSError):
raise IOError(_('Include file %r not found or reading it failed') % filename)
raise IOError('Include file %r not found or reading it failed' % filename)
except UnicodeError:
raise UnicodeError(_('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option') %
(self.encoding, filename))
raise UnicodeError('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
class OnlineIncludeDirective(LiteralInclude):
@@ -69,7 +68,7 @@ class OnlineIncludeDirective(LiteralInclude):
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
self.set_source_info(retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
+1 -1
View File
@@ -13,5 +13,5 @@ octoprint.init => /etc/init.d/octoprint
## systemd
```
octoprint.service => /etc/systemd/service/octoprint.service
octoprint.service => /etc/systemd/system/octoprint.service
```
+44 -30
View File
@@ -17,6 +17,11 @@ import setuptools
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
# Requirements for setup.py
SETUP_REQUIRES = [
"markdown>=3.1,<3.2",
]
# Requirements for our application
INSTALL_REQUIRES = [
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
@@ -27,7 +32,7 @@ INSTALL_REQUIRES = [
# guarantee backwards compatibility for plugins and such with that
# version, hence we need to pin to a lower version for now. See #1697
"tornado==4.5.3", # a memory leak was observed in tornado >= 5, see #2585
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
@@ -35,10 +40,10 @@ INSTALL_REQUIRES = [
"Flask-Principal>=0.4,<0.5",
"Flask-Babel>=0.12,<0.13",
"Flask-Assets>=0.12,<0.13",
"werkzeug>=0.15.1,<0.16",
"werkzeug>=0.16,<0.17",
"cachelib>=0.1,<0.2",
"PyYAML>=5.1,<6",
"markdown>=3.0,<3.1",
"markdown>=3.1,<3.2",
"pyserial>=3.4,<3.5",
"netaddr>=0.7.19,<0.8",
"watchdog>=0.9.0,<0.10",
@@ -47,41 +52,42 @@ INSTALL_REQUIRES = [
"pylru>=1.2,<1.3",
"rsa>=4.0,<5",
"pkginfo>=1.5.0.1,<1.6",
"requests>=2.21.0,<3",
"semantic_version>=2.6,<2.7",
"psutil>=5.6.1,<5.7",
"requests>=2.22.0,<3",
"semantic_version>=2.8,<2.9",
"psutil>=5.6.5,<5.7",
"Click>=7,<8",
"awesome-slugify>=1.6.5,<1.7",
"feedparser>=5.2.1,<5.3",
"future>=0.17,<0.18",
"future>=0.18.2,<0.19",
"websocket-client>=0.56,<0.57",
"wrapt>=1.11.1,<1.12",
"emoji>=0.5.1,<0.6",
"wrapt>=1.11.2,<1.12",
"emoji>=0.5.4,<0.6",
"frozendict>=1.2,<1.3",
"sentry-sdk==0.7.7"
"sentry-sdk==0.13.2",
"filetype>=1.0.5,<2"
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.2,<3.3",
"futures>=3.3,<3.4",
"monotonic>=1.5,<1.6",
"scandir>=1.10,<1.11",
"chainmap>=1.0.3,<1.1",
"typing>=3.6.6,<4"
"typing>=3.7.4.1,<4"
]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.0",
"appdirs>=1.4.3",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=2.0.0,<3",
"pytest>=4.2.1,<5.0",
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.6",
"pytest-doctest-custom>=1.0.0,<1.1",
"ddt",
@@ -89,10 +95,11 @@ EXTRA_REQUIRES = dict(
"flake8",
# Documentation dependencies
"sphinx>=1.6,<1.7",
"sphinx>=1.8.5,<2",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid>=0.3",
"sphinxcontrib-mermaid>=0.3.1",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext==0.5.17" # Later versions require Jinja >= 2.9
],
# Dependencies for developing OctoPrint plugins
@@ -131,14 +138,14 @@ def read_file_contents(path):
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):
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
def run(self):
import shutil
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.__class__.files.items():
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
@@ -146,16 +153,22 @@ def data_copy_build_py_factory(files, baseclass):
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = dest = entry
shutil.copy(source, os.path.join(target_dir, dest))
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
from markdown import markdownFromFile
markdownFromFile(input=source,
output=dest,
encoding="utf-8")
baseclass.run(self)
return type(data_copy_build_py)(data_copy_build_py.__name__,
(data_copy_build_py,),
dict(files=files))
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
(md_to_html_build_py,),
dict(files=files))
def get_cmdclass():
cmdclass = versioneer.get_cmdclass()
@@ -169,10 +182,9 @@ def get_cmdclass():
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
cmdclass["build_py"] = data_copy_build_py_factory({
cmdclass["build_py"] = md_to_html_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"CHANGELOG.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
@@ -191,6 +203,7 @@ def params():
long_description_content_type = "text/markdown"
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
@@ -215,6 +228,7 @@ def params():
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
+10 -40
View File
@@ -233,12 +233,6 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
},
"serial": {
"format": "%(asctime)s - %(message)s"
},
"communication": {
"format": "%(asctime)s - %(name)s - %(message)s"
},
"commdebug": {
"format": "%(asctime)s - %(threadName)s - %(message)s"
}
},
"handlers": {
@@ -256,45 +250,19 @@ def init_logging(settings, use_logging_file=True, logging_file=None, default_con
"backupCount": 6,
"filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log")
},
"protocolFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"serialFile": {
"class": "octoprint.logging.handlers.SerialLogHandler",
"level": "DEBUG",
"formatter": "communication",
"formatter": "serial",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "protocol.log"),
"delay": True
},
"transportFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "communication",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "transport.log"),
"delay": True
},
"commDebugFile": {
"class": "octoprint.logging.handlers.CommunicationLogHandler",
"level": "DEBUG",
"formatter": "commdebug",
"backupCount": 3,
"filename": os.path.join(settings.getBaseFolder("logs"), "commdebug.log"),
"filename": os.path.join(settings.getBaseFolder("logs"), "serial.log"),
"delay": True
}
},
"loggers": {
"PROTOCOL": {
"level": "DEBUG",
"handlers": ["protocolFile"],
"propagate": False
},
"TRANSPORT": {
"level": "DEBUG",
"handlers": ["transportFile"],
"propagate": False
},
"COMMDEBUG": {
"level": "DEBUG",
"handlers": ["commDebugFile"],
"SERIAL": {
"level": "INFO",
"handlers": ["serialFile"],
"propagate": False
},
"octoprint": {
@@ -442,7 +410,9 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti
if not startup:
return
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, x[2], x[0]))
from octoprint.util import sv
sorted_disabled_from_overlays = sorted([(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])))
disabled_list = pm.plugin_disabled_list
already_processed = []
+47 -22
View File
@@ -19,15 +19,18 @@ import logging
# noinspection PyCompatibility
from builtins import range, bytes
from octoprint.settings import settings
from octoprint.settings import settings as s
from octoprint.util import atomic_write, to_bytes, deprecated, monotonic_time
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.access.permissions import Permissions, OctoPrintPermission
from octoprint.access.groups import GroupChangeListener, Group
from past.builtins import basestring
class UserManager(GroupChangeListener, object):
def __init__(self, group_manager):
def __init__(self, group_manager, settings=None):
self._group_manager = group_manager
self._group_manager.register_listener(self)
@@ -36,6 +39,10 @@ class UserManager(GroupChangeListener, object):
self._sessionids_by_userid = dict()
self._enabled = True
if settings is None:
settings = s()
self._settings = settings
self._login_status_listeners = []
def register_login_status_listener(self, listener):
@@ -92,14 +99,15 @@ class UserManager(GroupChangeListener, object):
try:
listener.on_user_logged_in(user)
except Exception:
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener))
self._logger.exception("Error in on_user_logged_in on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged in user: %r" % user)
return user
def logout_user(self, user):
if user is None or user.is_anonymous:
if user is None or user.is_anonymous or isinstance(user, AdminUser):
return
if isinstance(user, LocalProxy):
@@ -124,28 +132,31 @@ class UserManager(GroupChangeListener, object):
try:
listener.on_user_logged_out(user)
except Exception:
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener))
self._logger.exception("Error in on_user_logged_out on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
self._logger.debug("Logged out user: %r" % user)
def _cleanup_sessions(self):
for session, user in self._session_users_by_session.items():
for session, user in list(self._session_users_by_session.items()):
if not isinstance(user, SessionUser):
continue
if user.created + (24 * 60 * 60) < monotonic_time():
self.logout_user(user)
@staticmethod
def create_password_hash(password, salt=None):
def create_password_hash(password, salt=None, settings=None):
if not salt:
salt = settings().get(["accessControl", "salt"])
if settings is None:
settings = s()
salt = settings.get(["accessControl", "salt"])
if salt is None:
import string
from random import choice
chars = string.ascii_lowercase + string.ascii_uppercase + string.digits
salt = "".join(choice(chars) for _ in range(32))
settings().set(["accessControl", "salt"], salt)
settings().save()
settings.set(["accessControl", "salt"], salt)
settings.save()
return hashlib.sha512(to_bytes(password, encoding="utf-8", errors="replace") + to_bytes(salt)).hexdigest()
@@ -154,13 +165,16 @@ class UserManager(GroupChangeListener, object):
if not user:
return False
hash = UserManager.create_password_hash(password)
hash = UserManager.create_password_hash(password,
settings=self._settings)
if user.check_password(hash):
# new hash matches, correct password
return True
else:
# new hash doesn't match, but maybe the old one does, so check that!
oldHash = UserManager.create_password_hash(password, salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW")
oldHash = UserManager.create_password_hash(password,
salt="mvBUTvwzBzD3yPwvnJ4E4tXNf3CGJvvW",
settings=self._settings)
if user.check_password(oldHash):
# old hash matches, we migrate the stored password hash to the new one and return True since it's the correct password
self.change_user_password(username, password)
@@ -261,7 +275,8 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def on_group_subgroups_changed(self, group, added=None, removed=None):
users = self.find_sessions_for(lambda u: group in u.groups)
@@ -271,7 +286,8 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def _trigger_on_user_modified(self, user):
if isinstance(user, basestring):
@@ -300,14 +316,16 @@ class UserManager(GroupChangeListener, object):
for user in users:
listener.on_user_modified(user)
except Exception:
self._logger.exception("Error in on_user_modified on {!r}".format(listener))
self._logger.exception("Error in on_user_modified on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
def _trigger_on_user_removed(self, username):
for listener in self._login_status_listeners:
try:
listener.on_user_removed(username)
except Exception:
self._logger.exception("Error in on_user_removed on {!r}".format(listener))
self._logger.exception("Error in on_user_removed on {!r}".format(listener),
extra=dict(callback=fqcn(listener)))
#~~ Deprecated methods follow
@@ -428,13 +446,13 @@ class LoginStatusListener(object):
##~~ FilebasedUserManager, takes available users from users.yaml file
class FilebasedUserManager(UserManager):
def __init__(self, group_manager, path=None):
UserManager.__init__(self, group_manager)
def __init__(self, group_manager, path=None, settings=None):
UserManager.__init__(self, group_manager, settings=settings)
if path is None:
path = settings().get(["accessControl", "userfile"])
path = self._settings.get(["accessControl", "userfile"])
if path is None:
path = os.path.join(settings().getBaseFolder("base"), "users.yaml")
path = os.path.join(s().getBaseFolder("base"), "users.yaml")
self._userfile = path
@@ -537,7 +555,13 @@ class FilebasedUserManager(UserManager):
if username in self._users and not overwrite:
raise UserAlreadyExists(username)
self._users[username] = User(username, UserManager.create_password_hash(password), active, permissions, groups, apikey=apikey)
self._users[username] = User(username,
UserManager.create_password_hash(password,
settings=self._settings),
active,
permissions,
groups,
apikey=apikey)
self._dirty = True
self._save()
@@ -670,7 +694,8 @@ class FilebasedUserManager(UserManager):
if not username in self._users:
raise UnknownUser(username)
passwordHash = UserManager.create_password_hash(password)
passwordHash = UserManager.create_password_hash(password,
settings=self._settings)
user = self._users[username]
if user._passwordHash != passwordHash:
user._passwordHash = passwordHash
+2 -1
View File
@@ -138,9 +138,10 @@ from .dev import dev_commands
from .client import client_commands
from .config import config_commands
from .analysis import analysis_commands
from .user import user_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands])
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
+184
View File
@@ -0,0 +1,184 @@
# 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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
import logging
from octoprint import init_settings
from octoprint.cli import get_ctx_obj_option
from octoprint.access.groups import FilebasedGroupManager
from octoprint.access.users import FilebasedUserManager, UnknownUser, UserAlreadyExists
from octoprint.util import get_class, sv
click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
@click.group()
def user_commands():
pass
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
"""
User management.
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo("Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
group_manager = FilebasedGroupManager()
ctx.obj.group_manager = group_manager
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
ctx.obj.user_manager = user_manager
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
@user.command(name="list")
@click.pass_context
def list_users_command(ctx):
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for the user")
@click.option("-g", "--group", "groups", multiple=True,
help="Groups to set on the user")
@click.option("-p", "--permission", "permissions", multiple=True,
help="Individual permissions to set on the user")
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Adds user to admin group")
@click.pass_context
def add_user_command(ctx, username, password, groups, permissions, is_admin):
"""Add a new user."""
if not groups:
groups = []
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
try:
ctx.obj.user_manager.add_user(username,
password,
groups=groups,
permissions=permissions,
active=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo("A user with the name {} does already exist!".format(username), err=True)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
"""Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
@user.command(name="password")
@click.argument("username", type=click.STRING)
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="activate")
@click.argument("username", type=click.STRING)
@click.pass_context
def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="deactivate")
@click.argument("username", type=click.STRING)
@click.pass_context
def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
click.echo("\t{}".format(_user_to_line(user)))
def _user_to_line(user):
return "{name}" \
"\n\t\tactive: {active}" \
"\n\t\tgroups: {groups}" \
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])))
-7
View File
@@ -1,7 +0,0 @@
# -*- 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"
-215
View File
@@ -1,215 +0,0 @@
# -*- 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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
import os
import io
try:
from os import scandir
except ImportError:
from scandir import scandir
from octoprint.settings import settings
from octoprint.util import is_hidden_path
class ConnectionProfile(object):
def __init__(self, id, name=None, printer_profile=None, protocol=None, protocol_parameters=None, transport=None, transport_parameters=None, **kwargs):
self.id = id
self.name = name if name is not None else id
self.printer_profile = printer_profile
self.protocol = protocol
self.protocol_parameters = protocol_parameters
self.transport = transport
self.transport_parameters = transport_parameters
@classmethod
def from_dict(cls, data):
identifier = data.pop("id")
return ConnectionProfile(identifier, **data)
def as_dict(self):
return dict(id=self.id,
name=self.name,
printer_profile=self.printer_profile,
protocol=self.protocol,
protocol_parameters=self.protocol_parameters,
transport=self.transport,
transport_parameters=self.transport_parameters)
class ConnectionProfileManager(object):
@classmethod
def to_profile(cls, data):
return ConnectionProfile.from_dict(data)
def __init__(self):
self._current = None
self._folder = settings().getBaseFolder("connectionProfiles")
self._logger = logging.getLogger(__name__)
def select(self, identifier):
self._current = self.get(identifier)
if self._current is None:
self._logger.error("Profile {} is invalid, cannot select".format(identifier))
return False
return True
def deselect(self):
self._current = None
@property
def current(self):
return self._current
def get_all(self):
return self._load_all()
def get(self, identifier):
try:
if self.exists(identifier):
return self._load_from_path(self._get_profile_path(identifier))
else:
return None
except InvalidProfileError:
return None
def remove(self, identifier):
return self._remove_from_path(self._get_profile_path(identifier))
def save(self, profile, allow_overwrite=False, make_default=False):
self._save_to_path(self._get_profile_path(profile.id),
profile,
allow_overwrite=allow_overwrite)
if make_default:
self.set_default(profile.id)
return self.get(profile.id)
@property
def profile_count(self):
return len(self._load_all_identifiers())
@property
def last_modified(self):
dates = [os.stat(self._folder).st_mtime]
dates += [entry.stat().st_mtime for entry in scandir(self._folder) if entry.name.endswith(".profile")]
return max(dates)
def get_default(self):
default = settings().get(["connectionProfiles", "default"])
if default is not None and self.exists(default):
profile = self.get(default)
if profile is not None:
return profile
else:
self._logger.warning("Default profile {} is invalid".format(default))
return None
def set_default(self, identifier):
all_identifiers = self._load_all_identifiers()
if identifier is not None and identifier not in all_identifiers:
return
settings().set(["connectionProfiles", "default"], identifier)
settings().save()
def get_current_or_default(self):
if self._current is not None:
return self._current
else:
return self.get_default()
def get_current(self):
return self._current
def exists(self, identifier):
if identifier is None:
return False
path = self._get_profile_path(identifier)
return os.path.exists(path) and os.path.isfile(path)
def _load_all(self):
all_identifiers = self._load_all_identifiers()
results = dict()
for identifier, path in all_identifiers.items():
try:
profile = self._load_from_path(path)
except InvalidProfileError:
self._logger.warning("Profile {} is invalid, skipping".format(identifier))
continue
if profile is None:
continue
results[identifier] = profile
return results
def _load_all_identifiers(self):
results = dict()
for entry in scandir(self._folder):
if is_hidden_path(entry.name) or not entry.name.endswith(".profile"):
continue
if not entry.is_file():
continue
identifier = entry.name[:-len(".profile")]
results[identifier] = entry.path
return results
def _load_from_path(self, path):
if not os.path.exists(path) or not os.path.isfile(path):
return None
import yaml
with io.open(path, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if data is None or not isinstance(data, dict):
raise InvalidProfileError("Profile is None or not a dict")
return ConnectionProfile.from_dict(data)
def _save_to_path(self, path, profile, allow_overwrite=False):
if os.path.exists(path) and not allow_overwrite:
raise SaveError("Profile {} already exists and overwriting is not allowed".format(profile["id"]))
from octoprint.util import atomic_write
import yaml
try:
with atomic_write(path, mode="wt", max_permissions=0o666) as f:
yaml.safe_dump(profile.as_dict(), f,
default_flow_style=False,
indent=2,
allow_unicode=True)
except Exception as e:
self._logger.exception("Error while trying to save profile {}".format(profile["id"]))
raise SaveError("Cannot save profile {}: {}".format(profile["id"], e))
def _remove_from_path(self, path):
try:
os.remove(path)
return True
except Exception:
return False
def _get_profile_path(self, identifier):
return os.path.join(self._folder, "{}.profile".format(identifier))
class InvalidProfileError(Exception):
pass
class SaveError(Exception):
pass
-573
View File
@@ -1,573 +0,0 @@
# -*- 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 logging
import os
import copy
from octoprint.comm.protocol import ProtocolListener, FileAwareProtocolListener, ProtocolState, FileManagementProtocolMixin
from octoprint.util.listener import ListenerAware
from abc import ABCMeta, abstractmethod, abstractproperty
from octoprint.util import monotonic_time
from future.utils import with_metaclass
class LastResult(object):
def __init__(self):
self.elapsed = None
self.clean_elapsed = None
self.progress = None
self.pos = None
self.success = None
self.available = False
class Printjob(with_metaclass(ABCMeta, ProtocolListener, ListenerAware)):
parallel = False
"""Job runs parallel to regular communication."""
exclusive = False
"""Job has exclusive claim to communication channel."""
def __init__(self, name=None, user=None, event_data=None):
if event_data is None:
event_data = dict()
super(Printjob, self).__init__()
self._logger = logging.getLogger(__name__)
self._start = None
self._protocol = None
self._printer_profile = None
self._name = name
self._user = user
self._event_data = event_data
self._lost_time = 0
self._last_result = LastResult()
@property
def name(self):
return self._name
@property
def user(self):
return self._user
@property
def size(self):
return None
@property
def pos(self):
return None
@property
def elapsed(self):
return monotonic_time() - self._start if self._start is not None else None
@property
def clean_elapsed(self):
elapsed = self.elapsed
if elapsed is None:
return None
return elapsed - self._lost_time
@property
def last_result(self):
return self._last_result
@property
def progress(self):
size = self.size
pos = self.pos
if pos is None or size is None or size == 0:
return None
return float(pos) / float(size)
@property
def active(self):
return self._start is not None
def add_to_lost_time(self, value):
self._lost_time += value
def can_process(self, protocol):
return False
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
self._last_result = LastResult()
self._start = monotonic_time()
self._user = user
self._protocol = protocol
self._protocol.register_listener(self)
def pause(self, user=None, tags=None, **kwargs):
self.process_job_paused(user=user, tags=tags, **kwargs)
def resume(self, user=None, tags=None, **kwargs):
self.process_job_resumed(user=user, tags=tags, **kwargs)
def cancel(self, error=False, user=None, tags=None, **kwargs):
if error:
self.process_job_failed(**kwargs)
else:
self.process_job_cancelled(user=user, tags=tags, **kwargs)
self._protocol.unregister_listener(self)
self._protocol = None
def get_next(self):
return None
def can_get_content(self):
return False
def get_content_generator(self):
return None
def event_payload(self, incl_last=False):
payload = copy.deepcopy(self._event_data)
payload["owner"] = self._user
elapsed = self.elapsed
if elapsed is None and incl_last and self.last_result.available:
elapsed = self.last_result.elapsed
if elapsed is not None:
payload["time"] = elapsed
return payload
def process_job_started(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_started", self, user=user, tags=tags, **kwargs)
def process_job_done(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_done", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job()
def process_job_failed(self, **kwargs):
self.notify_listeners("on_job_failed", self, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_cancelled", self, user=user, tags=tags, **kwargs)
self.report_stats()
self.reset_job(success=False)
def process_job_paused(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_paused", self, user=user, tags=tags, **kwargs)
def process_job_resumed(self, user=None, tags=None, **kwargs):
self.notify_listeners("on_job_resumed", self, user=user, tags=tags, **kwargs)
def process_job_progress(self):
self.notify_listeners("on_job_progress", self)
def report_stats(self):
elapsed = self.elapsed
if elapsed:
self._logger.info("Job processed in {}s".format(elapsed))
def reset_job(self, success=True):
self._last_result.progress = 1.0 if success else self.progress
self._last_result.pos = self.size if success else self.pos
self._last_result.elapsed = self.elapsed
self._last_result.clean_elapsed = self.clean_elapsed
self._last_result.success = success
self._last_result.available = True
self._start = None
self._lost_time = 0
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
if new_state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR) and self.active:
self.cancel(error=True)
class StoragePrintjob(Printjob):
def __init__(self, storage, path_in_storage, *args, **kwargs):
Printjob.__init__(self, *args, **kwargs)
self._storage = storage
self._path_in_storage = path_in_storage
@property
def storage(self):
return self._storage
@property
def path_in_storage(self):
return self._path_in_storage
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["name"] = self.name
payload["path"] = self.path_in_storage
payload["origin"] = self.storage
return payload
class LocalFilePrintjob(StoragePrintjob):
def __init__(self, path, *args, **kwargs):
encoding = kwargs.pop("encoding", "utf-8")
StoragePrintjob.__init__(self, *args, **kwargs)
if path is None or not os.path.exists(path):
raise ValueError("path must be set to a local file path")
self._path = path
self._encoding = encoding
self._size = os.stat(path).st_size
self._pos = 0
self._read_lines = 0
self._actual_lines = 0
self._cancel_pos = None
self._handle = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._pos
@property
def actual_lines(self):
return self._actual_lines
@property
def read_lines(self):
return self._read_lines
@property
def cancel_pos(self):
return self._cancel_pos
@property
def active(self):
return self._start is not None and self._handle is not None
@property
def path(self):
return self._path
def event_payload(self, incl_last=False):
event_data = StoragePrintjob.event_payload(self, incl_last=incl_last)
event_data["size"] = self.size
return event_data
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
from octoprint.util import bom_aware_open
self._handle = bom_aware_open(self._path, encoding=self._encoding, errors="replace")
if position > 0:
self._handle.seek(position)
self._pos = position
self.process_job_started(user=user, tags=tags)
def cancel(self, error=False, user=None, tags=None, **kwargs):
self._cancel_pos = self.pos
super(LocalFilePrintjob, self).cancel(error=error, user=user, tags=tags, **kwargs)
def get_next(self):
from octoprint.util import to_unicode
if self._handle is None:
raise ValueError("File {} is not open for reading" % self._path)
try:
processed = None
while processed is None:
if self._handle is None:
# file got closed just now
self.process_job_done()
return None
line = to_unicode(self._handle.readline())
# we need to manually keep track of our pos here since
# codecs' readline will make our handle's tell not
# return the actual number of bytes read, but also the
# already buffered bytes (for detecting the newlines)
self._pos += len(line)
self._actual_lines += 1
if not line:
self.process_job_done()
return None
processed = self.process_line(line)
self._read_lines += 1
self.process_job_progress()
return processed
except Exception as e:
self.cancel(error=True)
self._logger.exception("Exception while processing line")
raise e
def process_line(self, line):
return line
def close(self):
if self._handle is not None:
try:
self._handle.close()
except Exception:
pass
self._handle = None
def can_get_content(self):
return True
def get_content_generator(self):
from octoprint.util import bom_aware_open
with bom_aware_open(self._path, encoding=self._encoding, error="replace") as f:
for line in f.readline():
yield line
def reset_job(self, success=True):
super(LocalFilePrintjob, self).reset_job(success=success)
self.close()
self._pos = self._read_lines = 0
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines)".format(elapsed, lines))
class LocalGcodeFilePrintjob(LocalFilePrintjob):
def can_process(self, protocol):
return LocalGcodeFilePrintjob in protocol.supported_jobs
def process_line(self, line):
# TODO no dependency on protocol module
from octoprint.comm.protocol.reprap.util import strip_comment
# strip line
processed = line.strip()
# strip comments
processed = strip_comment(processed)
if not len(processed):
return None
# TODO apply offsets
# return result
return processed
class CopyJobMixin(object):
pass
class LocalGcodeStreamjob(LocalGcodeFilePrintjob, CopyJobMixin):
exclusive = True
@classmethod
def from_job(cls, job, remote):
if not isinstance(job, LocalGcodeFilePrintjob):
raise ValueError("job must be a LocalGcodeFilePrintjob")
path = job._path
storage = job._storage
path_in_storage = job._path_in_storage
name = job._name
user = job._user
encoding = job._encoding
event_data = job._event_data
return cls(remote, path, storage, path_in_storage,
name=name, user=user, encoding=encoding, event_data=event_data)
def __init__(self, remote, *args, **kwargs):
super(LocalGcodeStreamjob, self).__init__(*args, **kwargs)
self._remote = remote
@property
def remote(self):
return self._remote
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
super(LocalGcodeStreamjob, self).process(protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.record_file(self._remote)
def process_job_done(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_done(user=user, tags=tags, **kwargs)
def process_job_failed(self, **kwargs):
self._protocol.stop_recording_file()
super(LocalGcodeStreamjob, self).process_job_failed(**kwargs)
def process_job_cancelled(self, user=None, tags=None, **kwargs):
self._protocol.stop_recording_file()
self._protocol.delete_file(self.remote)
super(LocalGcodeStreamjob, self).process_job_cancelled(user=user, tags=tags, **kwargs)
def can_process(self, protocol):
from octoprint.comm.protocol import FileStreamingProtocolMixin
return LocalGcodeStreamjob in protocol.supported_jobs and isinstance(protocol, FileStreamingProtocolMixin) and isinstance(protocol, FileManagementProtocolMixin)
def report_stats(self):
elapsed = self.elapsed
lines = self._read_lines
if elapsed and lines:
self._logger.info("Job processed in {:.3f}s ({} lines). Approx. {:.3f} lines/s, {:.3f} ms/line".format(elapsed,
lines,
float(lines) / float(elapsed),
float(elapsed) * 1000.0 / float(lines)))
class SDFilePrintjob(StoragePrintjob, FileAwareProtocolListener):
parallel = True
def __init__(self, path, status_interval=2.0, *args, **kwargs):
name = path
if name.startswith("/"):
name = name[1:]
StoragePrintjob.__init__(self,
"sdcard",
name,
name=name,
event_data=dict(name=name,
path=path,
origin="sdcard"))
self._filename = path
self._status_interval = status_interval
self._status_timer = None
self._active = False
self._size = None
self._last_pos = None
@property
def size(self):
return self._size
@property
def pos(self):
return self._last_pos
@property
def active(self):
return self._start is not None and self._active
@property
def status_interval(self):
return self._status_interval
def can_process(self, protocol):
from octoprint.comm.protocol import FileAwareProtocolMixin
return SDFilePrintjob in protocol.supported_jobs and isinstance(protocol, FileAwareProtocolMixin)
def process(self, protocol, position=0, user=None, tags=None, **kwargs):
Printjob.process(self, protocol, position=position, user=user, tags=tags, **kwargs)
self._protocol.register_listener(self)
self._active = True
self._last_pos = position
self._protocol.start_file_print(self._filename,
position=position,
user=user,
tags=tags,
part_of_job=True,
**kwargs)
self._protocol.start_file_print_status_monitor()
def pause(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).pause(user=user, tags=tags, **kwargs)
self._protocol.pause_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def resume(self, user=None, tags=None, **kwargs):
super(SDFilePrintjob, self).resume(user=user, tags=tags, **kwargs)
self._protocol.resume_file_print(user=user,
tags=tags,
part_of_job=True,
**kwargs)
def on_protocol_sd_status(self, protocol, pos, total):
self._last_pos = pos
self._size = total
self.process_job_progress()
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
self._size = size
self.process_job_started(**kwargs)
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
self._protocol.stop_file_print_status_monitor(**kwargs)
self.process_job_done(**kwargs)
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
self._protocol.pause_file_print(**kwargs)
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
self._protocol.resume_file_print(**kwargs)
def reset_job(self, success=True):
super(SDFilePrintjob, self).reset_job(success=success)
self._active = False
self._last_pos = None
self._size = None
def event_payload(self, incl_last=False):
payload = Printjob.event_payload(self, incl_last=incl_last)
payload["size"] = self.size
return payload
class PrintjobListener(object):
def on_job_started(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_done(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_failed(self, job, *args, **kwargs):
pass
def on_job_cancelling(self, job, firmware_error=None, *args, **kwargs):
pass
def on_job_cancelled(self, job, cancel_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_paused(self, job, pause_position=None, suppress_script=False, *args, **kwargs):
pass
def on_job_resumed(self, job, suppress_script=False, *args, **kwargs):
pass
def on_job_progress(self, job, *args, **kwargs):
pass
-542
View File
@@ -1,542 +0,0 @@
# -*- 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"
from octoprint.comm.transport import TransportListener, TransportState
from octoprint.plugin import plugin_manager
from octoprint.util import to_unicode, CountedEvent
from octoprint.util.listener import ListenerAware
from octoprint.settings import SubSettings
import contextlib
import copy
import logging
_registry = dict()
def register_protocols():
from .reprap import ReprapGcodeProtocol
logger = logging.getLogger(__name__)
# stock protocols
register_protocol(ReprapGcodeProtocol)
# more protocols provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.protocol.register")
for name, hook in hooks.items():
try:
protocols = hook()
for protocol in protocols:
try:
register_protocol(protocol)
except Exception:
logger.exception("Error while registering protocol class {} for plugin {}".format(protocol, name))
except Exception:
logger.exception("Error executing octoprint.comm.protocol.register hook for plugin {}".format(name))
def register_protocol(protocol_class):
if not hasattr(protocol_class, "key"):
raise ValueError("Protocol class {} is missing key".format(protocol_class))
_registry[protocol_class.key] = protocol_class
def lookup_protocol(key):
return _registry.get(key)
def all_protocols():
return _registry.values()
class Protocol(ListenerAware, TransportListener):
name = None
key = None
supported_jobs = []
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Protocol, self).__init__()
self._logger = logging.getLogger(__name__)
self._protocol_logger = logging.getLogger("PROTOCOL")
self._state = ProtocolState.DISCONNECTED
self._error = None
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, ProtocolSettings):
self._settings = ProtocolSettings(self._settings, self)
self._job = None
self._transport = None
self._job_on_hold = CountedEvent()
self._args = dict()
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@contextlib.contextmanager
def job_put_on_hold(self, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
raise RuntimeError("Could not acquire job_on_hold lock")
self._job_on_hold.set()
try:
yield
finally:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
self._job_on_hold.release()
@property
def job_on_hold(self):
return self._job_on_hold.counter > 0
def set_job_on_hold(self, value, blocking=True):
if not self._job_on_hold.acquire(blocking=blocking):
return False
try:
if value:
self._job_on_hold.set()
else:
self._job_on_hold.clear()
if self._job_on_hold.counter == 0:
self._job_on_hold_cleared()
finally:
self._job_on_hold.release()
return True
@property
def transport(self):
return self._transport
@property
def state(self):
return self._state
@state.setter
def state(self, new_state):
old_state = self._state
if old_state == new_state:
return
self._state = new_state
name = "_on_switching_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
self.process_protocol_log("--- Protocol state changed from '{}' to '{}'".format(old_state, new_state))
self.notify_listeners("on_protocol_state", self, old_state, new_state)
name = "_on_switched_state_{}".format(new_state)
method = getattr(self, name, None)
if method is not None:
method(old_state)
@property
def error(self):
return self._error
@error.setter
def error(self, new_error):
self._error = new_error
def connect(self, transport, transport_args=None, transport_kwargs=None):
if self.state not in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR):
raise ProtocolAlreadyConnectedError("Already connected, disconnect first")
self.process_protocol_log("--- Protocol {} connecting via transport {}...".format(self,
transport))
if transport_args is None:
transport_args = []
if transport_kwargs is None:
transport_kwargs = dict()
self._transport = transport
self._transport.register_listener(self)
if self._transport.state == TransportState.DISCONNECTED:
self._transport.connect(*transport_args, **transport_kwargs)
self.state = ProtocolState.CONNECTING
def disconnect(self, error=False):
if self.state in (ProtocolState.DISCONNECTED, ProtocolState.DISCONNECTED_WITH_ERROR, ProtocolState.DISCONNECTING, ProtocolState.DISCONNECTING_WITH_ERROR):
raise ProtocolNotConnectedError("Already disconnecting or disconnected")
if error:
self.state = ProtocolState.DISCONNECTING_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTING
self.process_protocol_log("--- Protocol {} disconnecting from transport {}...".format(self,
self._transport))
self._transport.unregister_listener(self)
if self._transport.state == TransportState.CONNECTED:
try:
self._transport.disconnect()
except Exception:
self._logger.exception("Error while disconnecting from transport {}".format(self._transport))
error = True
if error:
self.state = ProtocolState.DISCONNECTED_WITH_ERROR
else:
self.state = ProtocolState.DISCONNECTED
def process(self, job, position=0, user=None, tags=None, **kwargs):
if not job.can_process(self):
raise ValueError("Job {} cannot be processed with protocol {}".format(job, self))
self._job = job
self._job.register_listener(self)
self.state = ProtocolState.STARTING
self.notify_listeners("on_protocol_job_starting", self, self._job, user=user, tags=tags, **kwargs)
self._job.process(self, position=position, user=user, tags=tags, **kwargs)
def pause_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in ProtocolState.PROCESSING_STATES:
return
self.state = ProtocolState.PAUSING
self.notify_listeners("on_protocol_job_pausing", self, self._job, user=user, tags=tags, **kwargs)
self._job.pause(user=user, tags=tags)
def resume_processing(self, user=None, tags=None, **kwargs):
if self._job is None or self.state not in (ProtocolState.PAUSING, ProtocolState.PAUSED):
return
self.state = ProtocolState.RESUMING
self.notify_listeners("on_protocol_job_resuming", self, self._job, user=user, tags=tags, **kwargs)
self._job.resume(user=user, tags=tags, **kwargs)
def cancel_processing(self, error=False, user=None, tags=None, **kwargs):
if self._job is not None and self.state in ProtocolState.PROCESSING_STATES + (ProtocolState.PAUSED,):
self.state = ProtocolState.CANCELLING
self.notify_listeners("on_protocol_job_cancelling", self, self._job, user=user, tags=tags, **kwargs)
self._job.cancel(error=error, user=user, tags=tags, **kwargs)
def can_send(self):
return True
def send_commands(self, command_type=None, tags=None, *commands):
pass
def send_script(self, script, context=None, user=None, tags=None):
"""
Sends the specified script/the GCODE script with the specified name.
Args:
script (GcodeScript or unicode): Script or name of the script to send
context (dict): Additional render context
user (str): The user on whose behalf the script is being sent. May be None
tags (set): And tags to send with the script commands. May be None
"""
pass
def repair(self):
pass
def on_job_started(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_started", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_paused(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_paused", self, job, *args, **kwargs)
self.state = ProtocolState.PAUSED
def on_job_resumed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_resumed", self, job, *args, **kwargs)
self.state = ProtocolState.PROCESSING
def on_job_done(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_done", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_cancelled(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_cancelled", self, job, *args, **kwargs)
self._job_processed(job)
def on_job_failed(self, job, *args, **kwargs):
self.notify_listeners("on_protocol_job_failed", self, job, *args, **kwargs)
self._job_processed(job)
def _job_processed(self, job, *args, **kwargs):
self._job.unregister_listener(self)
self.state = ProtocolState.CONNECTED
def on_transport_disconnected(self, transport, error=None):
self.disconnect(error=error is not None)
def on_transport_log_received_data(self, transport, data):
message = "<<< {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_sent_data(self, transport, data):
message = ">>> {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def on_transport_log_message(self, transport, data):
message = "--- {}".format(to_unicode(data, errors="replace").strip())
self.process_protocol_log(message)
def process_protocol_log(self, message):
self._protocol_logger.info(message)
self.notify_listeners("on_protocol_log", self, message)
def _job_on_hold_cleared(self):
pass
def __str__(self):
return self.__class__.__name__
class ProtocolState(object):
CONNECTING = "connecting"
CONNECTED = "connected"
DISCONNECTING = "disconnecting"
DISCONNECTED = "disconnected"
STARTING = "starting"
PROCESSING = "processing"
FINISHING = "finishing"
CANCELLING = "cancelling"
PAUSING = "pausing"
RESUMING = "resuming"
PAUSED = "paused"
ERROR = "error"
DISCONNECTING_WITH_ERROR = "disconnecting_with_error"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
PROCESSING_STATES = (STARTING, PROCESSING, CANCELLING, PAUSING, RESUMING, FINISHING)
OPERATIONAL_STATES = (CONNECTED, PAUSED) + PROCESSING_STATES
class ProtocolSettings(SubSettings):
def __init__(self, settings, protocol):
SubSettings.__init__(self, settings, ["comm", "protocol", protocol.key],
defaults=protocol.get_settings_defaults())
class ProtocolAlreadyConnectedError(Exception):
pass
class ProtocolNotConnectedError(Exception):
pass
class ThreeAxisProtocolMixin(object):
def move(self, x=None, y=None, z=None, feedrate=None, relative=False, *args, **kwargs):
pass
def home(self, x=False, y=False, z=False, *args, **kwargs):
pass
class MultiToolProtocolMixin(object):
def change_tool(self, tool, *args, **kwargs):
pass
class ThreeDPrinterProtocolMixin(ThreeAxisProtocolMixin, MultiToolProtocolMixin):
def move(self, x=None, y=None, z=None, e=None, feedrate=None, relative=False, *args, **kwargs):
pass
def set_feedrate_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extrusion_multiplier(self, multiplier, *args, **kwargs):
pass
def set_extruder_temperature(self, temperature, tool=None, wait=False, *args, **kwargs):
pass
def set_bed_temperature(self, temperature, wait=False, *args, **kwargs):
pass
def set_chamber_temperature(self, temperature, wait=False, *args, **kwargs):
pass
class FanControlProtocolMixin(object):
def set_fan_speed(self, speed, *args, **kwargs):
pass
def get_fan_speed(self, speed, *args, **kwargs):
pass
class MotorControlProtocolMixin(object):
def enable_motors(self, *args, **kwargs):
self.set_motor_state(True)
def disable_motors(self, *args, **kwargs):
self.set_motor_state(False)
def set_motor_state(self, enabled, *args, **kwargs):
pass
def get_motor_state(self, *args, **kwargs):
pass
class PowerControlProtocolMixin(object):
def enable_power(self, *args, **kwargs):
self.set_power_state(True)
def disable_power(self, *args, **kwargs):
self.set_power_state(False)
def set_power_state(self, enabled, *args, **kwargs):
pass
def get_power_state(self, *args, **kwargs):
return None
class FileAwareProtocolMixin(object):
def init_file_storage(self, *args, **kwargs):
pass
def eject_file_storage(self, *args, **kwargs):
pass
def list_files(self, *args, **kwargs):
pass
def start_file_print(self, name, position=0, tags=None, *args, **kwargs):
pass
def pause_file_print(self, *args, **kwargs):
pass
def resume_file_print(self, *args, **kwargs):
pass
def get_file_print_status(self, *args, **kwargs):
pass
def start_file_print_status_monitor(self, *args, **kwargs):
pass
def stop_file_print_status_monitor(self, *args, **kwargs):
pass
class FileManagementProtocolMixin(FileAwareProtocolMixin):
def delete_file(self, name, *args, **kwargs):
pass
class FileStreamingProtocolMixin(FileManagementProtocolMixin):
def record_file(self, name, *args, **kwargs):
pass
def stop_recording_file(self, *args, **kwargs):
pass
class ProtocolListener(object):
def on_protocol_state(self, protocol, old_state, new_state, *args, **kwargs):
pass
def on_protocol_temperature(self, protocol, temperatures, *args, **kwargs):
pass
def on_protocol_log(self, protocol, message, *args, **kwargs):
pass
def on_protocol_reset(self, protocol, idle, *args, **kwargs):
pass
def on_protocol_job_started(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_pausing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_paused(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resuming(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_resumed(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelling(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_cancelled(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_finishing(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_done(self, protocol, job, *args, **kwargs):
pass
def on_protocol_job_failed(self, protocol, job, *args, **kwargs):
pass
class FileAwareProtocolListener(object):
def on_protocol_file_storage_available(self, protocol, available, *args, **kwargs):
pass
def on_protocol_file_list(self, protocol, files, *args, **kwargs):
pass
def on_protocol_file_status(self, protocol, pos, total, *args, **kwargs):
pass
def on_protocol_file_print_started(self, protocol, name, long_name, size, *args, **kwargs):
pass
def on_protocol_file_print_done(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_paused(self, protocol, *args, **kwargs):
pass
def on_protocol_file_print_resumed(self, protocol, *args, **kwargs):
pass
class PositionAwareProtocolListener(object):
def on_protocol_position_all_update(self, protocol, position, *args, **kwargs):
pass
def on_protocol_position_z_update(self, protocol, z, *args, **kwargs):
pass
class FirmwareDataAwareProtocolListener(object):
def on_protocol_firmware_info(self, protocol, info, *args, **kwargs):
pass
def on_protocol_firmware_capability(self, protocol, capability, enabled, capabilities, *args, **kwargs):
pass
File diff suppressed because it is too large. Load diff
@@ -1,93 +0,0 @@
# -*- 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 copy
import re
from future.utils import with_metaclass
from octoprint.util import pp
_compiled_regex_type = type(re.compile(r"a"))
def _is_compiled_regex(obj):
return isinstance(obj, _compiled_regex_type)
__registry = dict()
def _register_command_class(cls):
__registry[cls.__name__] = cls
def to_command(line, type=None, tags=None, **kwargs):
if isinstance(line, Command):
return line
for cls in __registry.values():
if cls.pattern:
# noinspection PyUnresolvedReferences,PyProtectedMember
if _is_compiled_regex(cls.pattern) and cls.pattern.match(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
elif callable(cls.pattern) and cls.pattern(line):
return cls.from_line(line, type=type, tags=tags, **kwargs)
return Command.from_line(line, type=type, tags=tags, **kwargs)
class CommandMetaClass(type):
def __new__(mcs, *args, **kwargs):
c = type.__new__(mcs, *args, **kwargs)
_register_command_class(c)
return c
class Command(with_metaclass(CommandMetaClass, object)):
pattern = None
@classmethod
def from_line(cls, line, type=None, tags=None, **kwargs):
return cls(line, type=type, tags=tags, **kwargs)
def __init__(self, line, type=None, tags=None, **kwargs):
if tags is None:
tags = set()
self.line = line
self.bytes = line.encode("ascii", errors="replace")
self.type = type
self.tags = tags
def __repr__(self):
return "{}({!r},type={!r},tags={})".format(self.__class__.__name__, self.line, self.type, pp(self.tags))
def __str__(self):
return self.line
def __bytes__(self):
return self.bytes
def __key(self):
return self.line, self.type
def __eq__(self, other):
return self.__key() == other.__key()
def __hash__(self):
return hash(self.__key())
def with_type(self, type):
c = copy.deepcopy(self)
c.type = type
return c
def with_tags(self, tags):
if tags is None:
return self
c = copy.deepcopy(self)
c.tags |= tags
return c
@@ -1,40 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.commands import Command
from octoprint.util import pp
class AtCommand(Command):
pattern = staticmethod(lambda x: x.startswith("@"))
@staticmethod
def from_line(line, **kwargs):
split = line.split(None, 1)
if len(split) == 2:
atcommand = split[0]
parameters = split[1]
else:
atcommand = split[0]
parameters = ""
atcommand = atcommand[1:]
return AtCommand(line, atcommand, parameters, **kwargs)
def __init__(self, line, atcommand, parameters, **kwargs):
self.atcommand = atcommand
self.parameters = parameters
super(AtCommand, self).__init__(line, **kwargs)
def __repr__(self):
return "AtCommand({!r},{!r},{!r},type={!r},tags={}".format(self.line,
self.atcommand,
self.parameters,
self.type,
pp(self.tags))
@@ -1,134 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.commands import Command
import re
import string
from octoprint.util import pp
class GcodeCommand(Command):
pattern = staticmethod(lambda x: GcodeCommand.command_regex.match(x))
command_regex = re.compile(r"^\s*((?P<GM>[GM](?P<number>\d+))(\\.(?P<subcode>\d+))?|(?P<T>T(?P<tool>\d+))|(?P<F>F(?P<feedrate>\d+)))")
parameter_regex = re.compile(r"(?P<key>[A-Z])((?P<value>[-+]?[0-9]*\.?[0-9]+)(?!\d)|(\s|$))")
possible_params = tuple(string.ascii_lowercase) + ("subcode", "param", "tool", "feedrate", "original")
@staticmethod
def from_line(line, **kwargs):
if isinstance(line, GcodeCommand):
return line
tags = kwargs.get("tags")
if tags is None:
tags = set()
command_type = kwargs.get("type")
line = line.strip()
code = ""
args = dict(original=line, type=command_type, tags=tags)
match = GcodeCommand.command_regex.match(line)
if match is None:
# not a gcode command
return Command.from_line(line, **kwargs)
if match.group("GM"):
code = match.group("GM")
if match.group("subcode"):
args["subcode"] = int(match.group("subcode"))
if match.group(0) != line:
rest = line[len(match.group(0)):]
while True:
matched_param = GcodeCommand.parameter_regex.search(rest)
if not matched_param:
break
key = matched_param.group("key").lower()
if matched_param.group("value"):
value = matched_param.group("value")
if "." in value:
value = float(value)
else:
value = int(value)
else:
value = True
args[key] = value
rest = rest[:matched_param.start()] + rest[matched_param.end():]
rest = rest.lstrip()
if rest:
args["param"] = rest
elif match.group("T"):
code = "T"
args["tool"] = int(match.group("tool"))
elif match.group("F"):
code = "F"
args["feedrate"] = int(match.group("feedrate"))
return GcodeCommand(code, **args)
def __init__(self, code, **kwargs):
self.code = code
self.subcode = kwargs.pop("subcode", None)
self.tool = kwargs.pop("tool", None)
self.feedrate = kwargs.pop("feedrate", None)
self.param = kwargs.pop("param", None)
self.original = kwargs.pop("original", None)
command_type = kwargs.pop("type", None)
tags = kwargs.pop("tags", None)
self.args = kwargs
if self.original is None:
line = self._to_line()
else:
line = self.original
super(GcodeCommand, self).__init__(line, type=command_type, tags=tags)
self._repr = self._to_repr()
def __getattr__(self, item):
if len(item) == 1:
return self.args.get(item, None)
raise AttributeError("'GcodeCommand' object has no attribute '{}'".format(item))
def __repr__(self):
return self._repr
def _to_line(self):
attr = []
for key in string.ascii_lowercase:
value = self.args.get(key, None)
if value is not None:
if value is True:
attr.append(key.upper())
else:
attr.append("{}{!r}".format(key.upper(), value))
attribute_str = " ".join(attr)
return "{}{}{}".format(self.code.upper(), " " + attribute_str if attribute_str else "",
" " + self.param if self.param else "")
def _to_repr(self):
args = [k + "=" + repr(getattr(self, k)) for k in self.possible_params if getattr(self, k, None) is not None]
return "GcodeCommand({!r}{},type={!r},tags={})".format(self.code,
"," + ",".join(args) if args else "",
self.type,
pp(self.tags))
@@ -1,44 +0,0 @@
# -*- 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"
from .generic import * # noqa: F403
from .klipper import * # noqa: F403
from .marlin import * # noqa: F403
from .repetier import * # noqa: F403
from .reprapfirmware import * # noqa: F403
from .smoothieware import * # noqa: F403
from .anet import * # noqa: F403
from .malyan import * # noqa: F403
class FlavorOverride(object):
def __init__(self, flavor, overrides):
self._flavor = flavor
self._overrides = overrides
@property
def flavor(self):
return self._flavor
@flavor.setter
def flavor(self, value):
self._flavor = value
@property
def overrides(self):
return self._overrides
@overrides.setter
def overrides(self, value):
self._overrides = value
def __getattr__(self, item):
try:
return self._overrides[item]
except KeyError:
return getattr(self._flavor, item)
@@ -1,17 +0,0 @@
# -*- 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"
from .repetier import RepetierFlavor
class AnetA8RepetierFlavor(RepetierFlavor):
key = "aneta8repetier"
name = "Anet A8"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "anet_a8" in firmware_name.lower()
@@ -1,706 +0,0 @@
# -*- 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 re
import logging
import time
from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
from octoprint.comm.protocol.reprap.util import regex_float_pattern, regex_positive_float_pattern, regex_int_pattern
from octoprint.util import chunks, monotonic_time
from future.utils import with_metaclass
_flavor_registry = dict()
def _register_flavor(cls):
key = getattr(cls, "key", None)
if key and not key in _flavor_registry:
_flavor_registry[key] = cls
def all_flavors():
return _flavor_registry.values()
def lookup_flavor(key):
return _flavor_registry.get(key)
class FlavorMeta(type):
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
_register_flavor(cls)
return cls
class GenericFlavor(with_metaclass(FlavorMeta, object)):
key = "generic"
name = "Generic Flavor"
logger = logging.getLogger(__name__)
unknown_requires_ack = False
unknown_with_checksum = False
always_send_checksum = False
never_send_checksum = False
detect_external_heatups = True
block_while_dwelling = False
trigger_ok_after_resend = "detect"
sd_relative_path = False
checksum_requiring_commands = ["M110"]
long_running_commands = ["G4", "G28", "G29", "G30", "G32", "M190", "M109", "M400", "M226"]
asynchronous_commands = ["G0", "G1", "G2", "G3"]
blocked_commands = ["M0", "M1"]
pausing_commands = ["M0", "M1", "M25"]
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = False
regex_resend_linenumber = re.compile(r"(N|N:)?(?P<n>%s)" % regex_int_pattern)
"""Regex to use for request line numbers in resend requests"""
regex_temp = re.compile(r"(?P<tool>B|T(?P<toolnum>\d*)):\s*(?P<actual>%s)(\s*/?\s*(?P<target>%s))?" % (
regex_positive_float_pattern, regex_positive_float_pattern))
"""Regex matching temperature entries in line.
Groups will be as follows:
* ``tool``: whole tool designator, incl. optional ``toolnum`` (str)
* ``toolnum``: tool number, if provided (int)
* ``actual``: actual temperature (float)
* ``target``: target temperature, if provided (float)
"""
regex_position = re.compile(r"(?P<axis>[XYZE]):(?P<pos>{float})\s*".format(float=regex_float_pattern))
"""Regex for matching position entries in line.
Groups will be as follows:
* ``axis``: axis designator, either ``X``, ``Y``, ``Z`` or ``E`` (str)
* ``pos``: axis position (float)
"""
regex_firmware_splitter = re.compile(r"\s*([A-Z0-9_]+):")
"""Regex to use for splitting M115 responses."""
regex_sd_file_opened = re.compile(r"file opened:\s*(?P<name>.*?)(\s+size:\s*(?P<size>[0-9]+)|$)")
regex_sd_printing_byte = re.compile(r"sd printing byte (?P<current>[0-9]*)/(?P<total>[0-9]*)")
"""Regex matching SD printing status reports.
Groups will be as follows:
* ``current``: current byte position in file being printed
* ``total``: total size of file being printed
"""
##~~ Overrides
_overrides = dict()
@classmethod
def with_overrides(cls, overrides):
return type(b"{}WithOverrides".format(cls.__name__), (cls,), overrides)
##~~ Identifier
@classmethod
def identifier(cls, firmware_name, firmware_info):
return False
##~~ Message matchers
@classmethod
def comm_timeout(cls, line, lower_line, state, flags):
now = monotonic_time()
matches = ((line == "" and now > flags["timeout"]) or (flags["expect_continous_comms"]
and not flags["job_on_hold"]
and not flags["long_running_command"]
and not flags["heating"]
and now > flags["ok_timeout"])) and \
(not cls.block_while_dwelling or not flags["dwelling_until"] or now > flags["dwelling_until"])
continue_further = line != ""
return matches, continue_further
@classmethod
def comm_ok(cls, line, lower_line, state, flags):
matches = lower_line.startswith("ok")
continue_further = not matches \
or cls.message_temperature(line, lower_line, state, flags) \
or cls.message_position(line, lower_line, state, flags) \
or cls.message_firmware_info(line, lower_line, state, flags)
return matches, continue_further
@classmethod
def comm_start(cls, line, lower_line, state, flags):
return lower_line == "start"
@classmethod
def comm_wait(cls, line, lower_line, state, flags):
return lower_line == "wait"
@classmethod
def comm_resend(cls, line, lower_line, state, flags):
return lower_line.startswith("resend") or lower_line.startswith("rs")
@classmethod
def comm_action_command(cls, line, lower_line, state, flags):
return line.startswith("//") and line[2:].strip().startswith("action:")
@classmethod
def comm_error(cls, line, lower_line, state, flags):
return line.startswith("Error:") or line.startswith("!!")
@classmethod
def comm_ignore_ok(cls, line, lower_line, state, flags):
return False
@classmethod
def comm_busy(cls, line, lower_line, state, flags):
return line.startswith("echo:busy:") or line.startswith("busy:")
@classmethod
def error_multiline(cls, line, lower_line, state, flags):
return False
@classmethod
def error_communication(cls, line, lower_line, state, flags):
return "line number" in lower_line or "checksum" in lower_line or "format error" in lower_line or "expected line" in lower_line
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return "T:" in line or "T0:" in line or "B:" in line
@classmethod
def message_position(cls, line, lower_line, state, flags):
return 'X:' in line and 'Y:' in line and 'Z:' in line
@classmethod
def message_firmware_info(cls, line, lower_line, state, flags):
return "NAME:" in line
@classmethod
def message_firmware_capability(cls, line, lower_line, state, flags):
return lower_line.startswith("cap:")
@classmethod
def message_sd_init_ok(cls, line, lower_line, state, flags):
return "sd card ok" in lower_line
@classmethod
def message_sd_init_fail(cls, line, lower_line, state, flags):
return "sd init fail" in lower_line or "volume.init failed" in lower_line or "openroot failed" in lower_line
@classmethod
def message_sd_file_opened(cls, line, lower_line, state, flags):
return lower_line.startswith("file opened")
@classmethod
def message_sd_file_selected(cls, line, lower_line, state, flags):
return lower_line.startswith("file selected")
@classmethod
def message_sd_begin_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("begin file list")
@classmethod
def message_sd_end_file_list(cls, line, lower_line, state, flags):
return lower_line.startswith("end file list")
@classmethod
def message_sd_printing_byte(cls, line, lower_line, state, flags):
return "sd printing byte" in lower_line
@classmethod
def message_sd_not_printing(cls, line, lower_line, state, flags):
return "not sd printing" in lower_line
@classmethod
def message_sd_done_printing(cls, line, lower_line, state, flags):
return "done printing file" in lower_line
@classmethod
def message_sd_begin_writing(cls, line, lower_line, state, flags):
return "writing to file" in lower_line
@classmethod
def message_sd_end_writing(cls, line, lower_line, state, flags):
return "done saving file" in lower_line
@classmethod
def message_sd_entry(cls, line, lower_line, state, flags):
return flags["sd_files_temp"] is not None
##~~ Message parsers
@classmethod
def parse_comm_error(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_timeout(cls, line, lower_line, state, flags):
return dict(line=line, lower_line=lower_line)
@classmethod
def parse_comm_action_command(cls, line, lower_line, state, flags):
action = line[2:].strip()[len("action:"):].strip()
return dict(line=line, lower_line=lower_line, action=action)
@classmethod
def parse_error_communication(cls, line, lower_line, state, flags):
if "line number" in lower_line or "expected line" in lower_line:
error_type = "linenumber"
elif "checksum" in lower_line:
error_type = "checksum"
else:
error_type = "other"
flags["last_communication_error"] = error_type
return dict(error_type=error_type)
@classmethod
def parse_comm_resend(cls, line, lower_line, state, flags):
line_to_resend = None
match = cls.regex_resend_linenumber.search(line)
if match is not None:
line_to_resend = int(match.group("n"))
return dict(linenumber=line_to_resend)
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
"""
Parses the provided temperature line.
The result will be a dictionary mapping from the extruder or bed key to
a tuple with current and target temperature. The result will be canonicalized
with :func:`canonicalize_temperatures` before returning.
Returns:
tuple: a 2-tuple with the maximum tool number and a dict mapping from
key to (actual, target) tuples, with key either matching ``Tn`` for ``n >= 0`` or ``B``
"""
current_tool = flags["current_tool"]
result = {}
max_tool_num = 0
for match in re.finditer(cls.regex_temp, line):
values = match.groupdict()
tool = values["tool"]
if tool == "T" and "toolnum" in values and values["toolnum"]:
tool_num = int(values["toolnum"])
if tool_num > max_tool_num:
max_tool_num = tool_num
try:
actual = float(values.get("actual", None)) if values.get("actual", None) is not None else None
target = float(values.get("target", None)) if values.get("target", None) is not None else None
result[tool] = actual, target
except ValueError:
# catch conversion issues, we'll rather just not get the temperature update instead of killing the connection
pass
heatup_detected = not lower_line.startswith("ok") and not flags["heating"] and not flags["temperature_autoreporting"]
return dict(max_tool_num=max(max_tool_num, current_tool),
temperatures=cls._canonicalize_temperatures(result, current_tool),
heatup_detected=heatup_detected)
@classmethod
def parse_message_position(cls, line, lower_line, state, flags):
position = dict(x=None, y=None, z=None, e=None)
for match in re.finditer(cls.regex_position, line):
position[match.group("axis").lower()] = float(match.group("pos"))
return dict(position=position)
@classmethod
def parse_message_firmware_info(cls, line, lower_line, state, flags):
data = cls._parse_firmware_line(line)
firmware_name = data.get("FIRMWARE_NAME")
if firmware_name is None:
# Malyan's "Marlin compatible firmware" isn't actually Marlin compatible and doesn't even
# report its firmware name properly in response to M115. Wonderful - why stick to established
# protocol when you can do your own thing, right?
#
# Example: NAME: Malyan VER: 2.9 MODEL: M200 HW: HA02
#
# We do a bit of manual fiddling around here to circumvent that issue and get ourselves a
# reliable firmware name (NAME + VER) out of the Malyan M115 response.
name = data.get("NAME")
ver = data.get("VER")
if "malyan" in name.lower() and ver:
firmware_name = name.strip() + " " + ver.strip()
if firmware_name is not None:
firmware_name = firmware_name.strip()
return dict(firmware_name=firmware_name,
data=data)
@classmethod
def parse_message_firmware_capability(cls, line, lower_line, state, flags):
result = cls._parse_capability_line(line)
if not result:
return
cap, enabled = result
return dict(cap=cap, enabled=enabled)
@classmethod
def parse_message_sd_file_opened(cls, line, lower_line, state, flags):
match = cls.regex_sd_file_opened.match(lower_line)
if not match:
return
name = match.group("name")
size = int(match.group("size"))
return dict(name=name, long_name=name, size=size)
@classmethod
def parse_message_sd_entry(cls, line, lower_line, state, flags):
fileinfo = lower_line.rsplit(None, 1)
if len(fileinfo) > 1:
# we might have extended file information here, so let's split filename and size and try to make them a bit nicer
filename, size = fileinfo
try:
size = int(size)
except ValueError:
# whatever that was, it was not an integer, so we'll just use the whole line as filename and set size to None
filename = lower_line
size = None
else:
# no extended file information, so only the filename is there and we set size to None
filename = lower_line
size = None
from octoprint.util import filter_non_ascii
if filter_non_ascii(filename):
return None
else:
if not filename.startswith("/"):
# file from the root of the sd -- we'll prepend a /
filename = "/" + filename
return dict(name=filename, long_name=filename, size=int(size) if size is not None else None)
@classmethod
def parse_message_sd_printing_byte(cls, line, lower_line, state, flags):
match = cls.regex_sd_printing_byte.match(lower_line)
if not match:
return None
return dict(current=int(match.group("current")), total=int(match.group("total")))
##~~ Commands
@classmethod
def command_hello(cls):
return cls.command_set_line(0)
@classmethod
def command_get_firmware_info(cls):
return GcodeCommand("M115")
@classmethod
def command_finish_moving(cls):
return GcodeCommand("M400")
@classmethod
def command_get_position(cls):
return GcodeCommand("M114")
@classmethod
def command_get_temp(cls):
return GcodeCommand("M105")
@classmethod
def command_set_line(cls, n):
return GcodeCommand("M110", n=n)
@classmethod
def command_emergency_stop(cls):
return GcodeCommand("M112")
@classmethod
def command_abort_heatup(cls):
return GcodeCommand("M108")
@classmethod
def command_set_extruder_temp(cls, temperature, tool=None, wait=False):
command = "M109" if wait else "M104"
args = dict(s=temperature)
if tool is not None:
args["t"] = tool
return GcodeCommand(command, **args)
@classmethod
def command_set_bed_temp(cls, temperature, wait=False):
return GcodeCommand("M190" if wait else "M140", s=temperature)
@classmethod
def command_set_chamber_temp(cls, temperature, wait=False):
return GcodeCommand("M191" if wait else "M141", s=temperature)
@classmethod
def command_set_relative_positioning(cls):
return GcodeCommand("G91")
@classmethod
def command_set_absolute_positioning(cls):
return GcodeCommand("G90")
@classmethod
def command_move(cls, x=None, y=None, z=None, e=None, f=None):
return GcodeCommand("G1", x=x, y=y, z=z, e=e, f=f)
@classmethod
def command_extrude(cls, e=None, f=None):
return cls.command_move(e=e, f=f)
@classmethod
def command_home(cls, x=False, y=False, z=False):
return GcodeCommand("G28", x=0 if x else None, y=0 if y else None, z=0 if z else None)
@classmethod
def command_set_tool(cls, tool):
return GcodeCommand("T{}".format(tool))
@classmethod
def command_set_feedrate_multiplier(cls, multiplier):
return GcodeCommand("M220", s=multiplier)
@classmethod
def command_set_extrusion_multiplier(cls, multiplier):
return GcodeCommand("M221", s=multiplier)
@classmethod
def command_set_fan_speed(cls, speed):
return GcodeCommand("M106", s=speed)
@classmethod
def command_set_motors(cls, enable):
return GcodeCommand("M17") if enable else GcodeCommand("M18")
@classmethod
def command_sd_refresh(cls):
return GcodeCommand("M20")
@classmethod
def command_sd_init(cls):
return GcodeCommand("M21")
@classmethod
def command_sd_release(cls):
return GcodeCommand("M22")
@classmethod
def command_sd_select_file(cls, name):
return GcodeCommand("M23", param=name)
@classmethod
def command_sd_start(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_pause(cls):
return GcodeCommand("M25")
@classmethod
def command_sd_resume(cls):
return GcodeCommand("M24")
@classmethod
def command_sd_set_pos(cls, pos):
return GcodeCommand("M26", s=pos)
@classmethod
def command_sd_status(cls):
return GcodeCommand("M27")
@classmethod
def command_sd_begin_write(cls, name):
return GcodeCommand("M28", param=name)
@classmethod
def command_sd_end_write(cls):
return GcodeCommand("M29")
@classmethod
def command_sd_delete(cls, name):
return GcodeCommand("M30", param=name)
@classmethod
def command_autoreport_temperature(cls, interval):
return GcodeCommand("M155", s=interval)
@classmethod
def command_autoreport_sd_status(cls, interval):
return GcodeCommand("M27", s=interval)
@classmethod
def command_busy_protocol_interval(cls, interval):
return GcodeCommand("M113", s=interval)
##~~ Helpers
@classmethod
def _canonicalize_temperatures(cls, parsed, current):
"""
Canonicalizes the temperatures provided in parsed.
Will make sure that returned result only contains extruder keys
like Tn, so always qualified with a tool number.
The algorithm for cleaning up the parsed keys is the following:
* If ``T`` is not included with the reported extruders, return
* If more than just ``T`` is reported:
* If both ``T`` and ``T0`` are reported set ``Tc`` to ``T``, remove
``T`` from the result.
* Else set ``T0`` to ``T`` and delete ``T`` (Smoothie extra).
* If only ``T`` is reported, set ``Tc`` to ``T`` and delete ``T``
* return
Arguments:
parsed (dict): the parsed temperatures (mapping tool => (actual, target))
to canonicalize
current (int): the current active extruder
Returns:
dict: the canonicalized version of ``parsed``
"""
reported_extruders = list(filter(lambda x: x.startswith("T"), parsed.keys()))
if not "T" in reported_extruders:
# Our reported_extruders are either empty or consist purely
# of Tn keys, no need for any action
return parsed
current_tool_key = "T%d" % current
result = dict(parsed)
if len(reported_extruders) > 1:
if "T0" in reported_extruders:
# Both T and T0 are present, so T contains the current
# extruder's temperature, e.g. for current_tool == 1:
#
# T:<T1> T0:<T0> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T1> T1:<T1> T2:<T2> ... B:<B>
#
# Same goes if Tc is already present, it will be overwritten:
#
# T:<T1> T0:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result[current_tool_key] = result["T"]
del result["T"]
else:
# So T is there, but T0 isn't. That looks like Smoothieware which
# always reports the first extruder T0 as T:
#
# T:<T0> T1:<T1> T2:<T2> ... B:<B>
#
# becomes
#
# T0:<T0> T1:<T1> T2:<T2> ... B:<B>
result["T0"] = result["T"]
del result["T"]
else:
# We only have T. That can mean two things:
#
# * we only have one extruder at all, or
# * we are currently parsing a response to M109/M190, which on
# some firmwares doesn't report the full M105 output while
# waiting for the target temperature to be reached but only
# reports the current tool and bed
#
# In both cases it is however safe to just move our T over
# to T<current> in the parsed data, current should always stay
# 0 for single extruder printers. E.g. for current_tool == 1:
#
# T:<T1>
#
# becomes
#
# T1:<T1>
result[current_tool_key] = result["T"]
del result["T"]
return result
@classmethod
def _parse_firmware_line(cls, line):
"""
Parses the provided firmware info line.
The result will be a dictionary mapping from the contained keys to the contained
values.
Arguments:
line (unicode): the line to parse
Returns:
dict: a dictionary with the parsed data
"""
result = dict()
split_line = cls.regex_firmware_splitter.split(line.strip())[1:] # first entry is empty start of trimmed string
for key, value in chunks(split_line, 2):
result[key] = value
return result
@classmethod
def _parse_capability_line(cls, line):
"""
Parses the provided firmware capability line.
Lines are expected to be of the format
Cap:<capability name in caps>:<0 or 1>
e.g.
Cap:AUTOREPORT_TEMP:1
Cap:TOGGLE_LIGHTS:0
Args:
line (unicode): the line to parse
Returns:
tuple: a 2-tuple of the parsed capability name and whether it's on (true) or off (false), or None if the line
could not be parsed
"""
line = line.lower()
if line.startswith("cap:"):
line = line[len("cap:"):]
parts = line.split(":")
if len(parts) != 2:
# wrong format, can't parse this
return None
capability, flag = parts
if not flag in ("0", "1"):
# wrong format, can't parse this
return None
return capability.upper(), flag == "1"
@@ -1,19 +0,0 @@
# -*- 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) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "klipper"
name = "Klipper"
unknown_requires_ack = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "klipper" in firmware_name.lower()
@@ -1,21 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MalyanFlavor(GenericFlavor):
key = "malyan"
name = "Malyan"
always_send_checksum = False
block_while_dwelling = True
sd_always_available = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "malyan" in firmware_name.lower()
@@ -1,35 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class MarlinFlavor(GenericFlavor):
key = "marlin"
name = "Marlin"
emergency_commands = ["M112", "M108", "M410"]
heatup_abortable = True
class MarlinLegacyFlavor(GenericFlavor):
key = "marlinlegacy"
name = "Legacy Marlin"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "marlin v1" in firmware_name.lower()
class PrusaMarlinFlavor(MarlinFlavor):
key = "prusamarlin"
name = "Marlin: Prusa variant"
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "prusa-firmware" in firmware_name.lower() and "marlin" in firmware_name.lower()
@@ -1,94 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.flavors import GenericFlavor
from octoprint.comm.protocol.reprap.util import regex_positive_float_pattern
import re
class RepetierFlavor(GenericFlavor):
key = "repetier"
name = "Repetier"
always_send_checksum = True
identical_resends_countdown = 5
block_while_dwelling = True
detect_external_heatups = False
regex_tempextr = re.compile("targetextr(?P<toolnum>\d+):(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier.
Groups will be as follows:
* ``toolnum``: number of the extruder to which the target temperature
report belongs (int)
* ``target``: new target temperature (float)
"""
regex_tempbed = re.compile("targetbed:(?P<target>%s)" % regex_positive_float_pattern)
"""Regex for matching target temp reporting from Repetier for beds.
Groups will be as follows:
* ``target``: new target temperature (float)
"""
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "repetier" in firmware_name.lower()
@classmethod
def message_temperature(cls, line, lower_line, state, flags):
return GenericFlavor.message_temperature(line, lower_line, state, flags) or "targetextr" in lower_line or "targetbed" in lower_line
@classmethod
def parse_message_temperature(cls, line, lower_line, state, flags):
if "targetextr" in lower_line:
match = cls.regex_tempextr.match(lower_line)
if match is not None:
tool_num = int(match.group("toolnum"))
target = float(match.group("target"))
tool = "T{}".format(tool_num)
temperatures = dict()
temperatures[tool] = (None, target)
return dict(max_tool_num=max(tool_num, flags.get("current_tool", 0)),
temperatures=temperatures,
heatup_detected=False)
elif "targetbed" in lower_line:
match = cls.regex_tempbed.match(lower_line)
if match is not None:
target = float(match.group("target"))
temperatures = dict(bed=(None, target))
return dict(max_tool_num=flags.get("current_tool", 0),
temperatures=temperatures,
heatup_detected=False)
else:
# Repetier sends temperature output on it's own line, so we can't use the
# "no ok in temperature output" metric to detected external heatups
result = GenericFlavor.parse_message_temperature(line, lower_line, state, flags)
result[b"heatup_detected"] = False
return result
##~~ Preprocessors, returning True stops further processing by the protocol
@classmethod
def preprocess_comm_resend(cls, linenumber, state, flags):
if flags.get("resend_swallow_repetitions", False) \
and flags.get("resend_swallow_repetitions_counter", 0) \
and linenumber == flags["resend_requested"] \
and flags["resend_swallow_repetitions_counter"] > 0:
cls.logger.debug("Ignoring resend request for line {}, that is "
"probably a repetition sent by the firmware to "
"ensure it arrives, not a real request"
.format(linenumber))
flags["resend_swallow_repetitions_counter"] -= 1
return True
flags["resend_swallow_repetitions_counter"] = cls.identical_resends_countdown
@@ -1,19 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "reprapfirmware"
name = "RepRapFirmware"
sd_relative_path = True
@classmethod
def identifier(cls, firmware_name, firmware_info):
return "reprapfirmware" in firmware_name.lower()
@@ -1,13 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.flavors.generic import GenericFlavor
class ReprapFirmwareFlavor(GenericFlavor):
key = "smoothieware"
name = "Smoothieware"
@@ -1,25 +0,0 @@
# -*- 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"
from octoprint.comm.scripts import Script, UnknownScript
from octoprint.comm.protocol.reprap.util import process_gcode_line
class GcodeScript(Script):
def __init__(self, settings, name, context=None):
def renderer(ctx):
lines = settings.loadScript("gcode", name, context=ctx)
if lines is None:
raise UnknownScript(name)
return lines
super(GcodeScript, self).__init__(name, renderer, context=context)
def render(self, context=None):
script = super(GcodeScript, self).render(context)
return list(filter(lambda x: x is not None and x.strip() != "",
map(lambda x: process_gcode_line(x),
script)))
@@ -1,398 +0,0 @@
# -*- 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"
from octoprint.comm.protocol.reprap.commands import Command, to_command
from octoprint.util import PrependableQueue, TypeAlreadyInQueue, CountedEvent
# noinspection PyCompatibility
from past.builtins import basestring
import contextlib
import copy
import logging
import threading
try:
# noinspection PyCompatibility
import queue
except Exception:
# noinspection PyCompatibility
import Queue as queue
regex_float_pattern = "[-+]?[0-9]*\.?[0-9]+"
regex_positive_float_pattern = "[+]?[0-9]*\.?[0-9]+"
regex_int_pattern = "\d+"
def strip_comment(line):
if not ";" in line:
# shortcut
return line
escaped = False
result = []
for c in line:
if c == ";" and not escaped:
break
result += c
escaped = (c == "\\") and not escaped
return "".join(result).strip()
def process_gcode_line(line, offsets=None, current_tool=None):
line = strip_comment(line).strip()
if not len(line):
return None
# if offsets is not None:
# line = apply_temperature_offsets(line, offsets, current_tool=current_tool)
return line
def normalize_command_handler_result(command, handler_results, tags_to_add=None):
"""
Normalizes a command handler result.
Handler results can be either ``None``, a single result entry or a list of result
entries.
``None`` results are ignored, the provided ``command``, ``command_type``,
``gcode``, ``subcode`` and ``tags`` are returned in that case (as single-entry list with
one 5-tuple as entry).
Single result entries are either:
* a single string defining a replacement ``command``
* a 1-tuple defining a replacement ``command``
* a 2-tuple defining a replacement ``command`` and ``command_type``
* a 3-tuple defining a replacement ``command`` and ``command_type`` and additional ``tags`` to set
A ``command`` that is ``None`` will lead to the entry being ignored for
the normalized result.
The method returns a list of normalized result entries. Normalized result
entries always are a 4-tuple consisting of ``command``, ``command_type``,
``gcode`` and ``subcode``, the latter three being allowed to be ``None``. The list may
be empty in which case the command is to be suppressed.
Examples:
>>> from octoprint.comm.protocol.reprap.commands.gcode import GcodeCommand
>>> normalize_command_handler_result(GcodeCommand("M105"), None) # doctest: +ALLOW_UNICODE
[GcodeCommand('M105',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), GcodeCommand("M110")) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110", "lineno_reset"), "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type='lineno_reset',tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), []) # doctest: +ALLOW_UNICODE
[]
>>> normalize_command_handler_result(GcodeCommand("M105"), ["M110", None]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), (None, "ignored")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105"), [("M110",), ("M117 Foobar", "display_message"), ("tuple", "of", "unexpected", "length"), ("M110", "lineno_reset")]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags=set()), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type='display_message',tags=set()), GcodeCommand('M110',original='M110',type='lineno_reset',tags=set())]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"]) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2'})]
>>> normalize_command_handler_result(GcodeCommand("M105",tags={"tag1", "tag2"}), ["M110", "M117 Foobar"], tags_to_add={"tag3"}) # doctest: +ALLOW_UNICODE
[GcodeCommand('M110',original='M110',type=None,tags={'tag1', 'tag2', 'tag3'}), GcodeCommand('M117',param='Foobar',original='M117 Foobar',type=None,tags={'tag1', 'tag2', 'tag3'})]
Arguments:
command (Command): The command for which the handler result was
generated
handler_results: The handler result(s) to normalized. Can be either
a single result entry or a list of result entries.
tags_to_add (set of unicode or None): List of tags to add to expanded result
entries
Returns:
(list) - A list of normalized handler result entries, which are
``Command`` instances
"""
original = command
if handler_results is None:
# handler didn't return anything, we'll just continue
return [original]
if not isinstance(handler_results, list):
handler_results = [handler_results, ]
result = []
for handler_result in handler_results:
# we iterate over all handler result entries and process each one
# individually here
if handler_result is None:
# entry is None, we'll ignore that entry and continue
continue
def expand_tags(tags, tags_to_add):
tags = tags.copy()
if tags_to_add and isinstance(tags_to_add, set):
tags |= tags_to_add
return tags
if isinstance(handler_result, basestring):
# entry is just a string, replace command with it
if handler_result != original.line:
# command changed, swap it
command = to_command(handler_result,
type=original.type,
tags=expand_tags(original.tags, tags_to_add))
result.append(command)
elif isinstance(handler_result, Command):
if handler_result != original:
command = copy.copy(handler_result)
command.tags = expand_tags(original.tags, tags_to_add)
result.append(command)
elif isinstance(handler_result, tuple):
# entry is a tuple, extract command and command_type
hook_result_length = len(handler_result)
command_type = original.type
command_tags = original.tags
if hook_result_length == 1:
# handler returned just the command
command_line, = handler_result
elif hook_result_length == 2:
# handler returned command and command_type
command_line, command_type = handler_result
elif hook_result_length == 3:
# handler returned command, command type and additional tags
command_line, command_type, command_tags = handler_result
else:
# handler returned a tuple of an unexpected length, ignore
# and continue
continue
if command_line is None:
# command is None, ignore it and continue
continue
if command_line != original.line or command_type != original.type:
# command or command_type changed, tags need to be rewritten
command_tags = expand_tags(command_tags, tags_to_add)
result.append(to_command(command_line, type=command_type, tags=command_tags))
# reset to original
command = original
return result
class SendToken(CountedEvent):
def __init__(self, value=0, maximum=None, **kwargs):
super(SendToken, self).__init__(value=value, maximum=maximum, **kwargs)
self._ignored = 0
def set(self, ignore=False):
with self._mutex:
if ignore:
self._ignored += 1
self._internal_set(self._counter + 1)
def clear(self, completely=False):
with self._mutex:
if completely:
self._internal_set(0)
self._ignored = 0
else:
if self._ignored > 0:
self._ignored -= 1
self._internal_set(self._counter - 1)
self._internal_set(self._counter - 1)
class LineHistory(object):
def __init__(self, max=None):
self.max = max
self._lines = []
self._mutex = threading.RLock()
self._line_number_lookup = dict()
@property
def lines(self):
with self._mutex:
return [x[0] for x in self._lines]
def append(self, line, line_number=None):
with self._mutex:
self._lines.append((line, line_number))
if line_number is not None:
self._line_number_lookup[line_number] = line
self._cleanup()
def clear(self):
with self._mutex:
self._lines = []
self._line_number_lookup = dict()
def __len__(self):
with self._mutex:
return len(self._lines)
def __getitem__(self, line_number):
with self._mutex:
return self._line_number_lookup[line_number]
def __contains__(self, line_number):
with self._mutex:
return line_number in self._line_number_lookup
def __iter__(self):
return iter(self.lines)
def _cleanup(self):
if len(self._lines) <= self.max:
return
while len(self._lines) > self.max:
_, line_number = self._lines.pop(0)
if line_number is not None:
try:
del self._line_number_lookup[line_number]
except KeyError:
pass
class PositionRecord(object):
_standard_attrs = {"x", "y", "z", "e", "f", "t"}
@classmethod
def valid_e(cls, attr):
if not attr.startswith("e"):
return False
try:
int(attr[1:])
except Exception:
return False
return True
def __init__(self, *args, **kwargs):
attrs = self._standard_attrs | set([key for key in kwargs if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, kwargs.get(attr))
def copy_from(self, other):
# make sure all standard attrs and attrs from other are set
attrs = self._standard_attrs | set([key for key in dir(other) if self.valid_e(key)])
for attr in attrs:
setattr(self, attr, getattr(other, attr))
# delete attrs other doesn't have
attrs = set([key for key in dir(self) if self.valid_e(key)]) - attrs
for attr in attrs:
delattr(self, attr)
def as_dict(self):
attrs = self._standard_attrs | set([key for key in dir(self) if self.valid_e(key)])
return dict((attr, getattr(self, attr)) for attr in attrs)
class TemperatureRecord(object):
def __init__(self):
self._tools = dict()
self._bed = (None, None)
self._chamber = (None, None)
def copy_from(self, other):
self._tools = other.tools
self._bed = other.bed
self._chamber = other.chamber
def set_tool(self, tool, actual=None, target=None):
current = self._tools.get(tool, (None, None))
self._tools[tool] = self._to_new_tuple(current, actual, target)
def set_bed(self, actual=None, target=None):
current = self._bed
self._bed = self._to_new_tuple(current, actual, target)
def set_chamber(self, actual=None, target=None):
current = self._chamber()
self._chamber = self._to_new_tuple(current, actual, target)
@property
def tools(self):
return dict(self._tools)
@property
def bed(self):
return self._bed
@property
def chamber(self):
return self._chamber
def as_dict(self):
result = dict()
tools = self.tools
for tool, data in tools.items():
result["tool{}".format(tool)] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["bed"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["chamber"] = dict(actual=chamber[0],
target=chamber[1])
return result
def as_script_dict(self):
result = self.as_dict()
# backwards compatibility
tools = self.tools
for tool, data in tools.items():
result[tool] = dict(actual=data[0],
target=data[1])
bed = self.bed
result["b"] = dict(actual=bed[0],
target=bed[1])
chamber = self.chamber
result["c"] = dict(actual=chamber[0],
target=chamber[1])
return result
@classmethod
def _to_new_tuple(cls, current, actual, target):
if current is None or not isinstance(current, tuple) or len(current) != 2:
current = (None, None)
if actual is None and target is None:
return current
old_actual, old_target = current
if actual is None:
return old_actual, target
elif target is None:
return actual, old_target
else:
return actual, target
@@ -1,194 +0,0 @@
# -*- 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"
from octoprint.util import PrependableQueue, TypedQueue, TypeAlreadyInQueue
try:
import queue
except ImportError:
import Queue as queue
import contextlib
import logging
import threading
class ScriptQueue(PrependableQueue):
pass
class JobQueue(PrependableQueue):
pass
class CommandQueue(TypedQueue):
def __init__(self, *args, **kwargs):
TypedQueue.__init__(self, *args, **kwargs)
self._unblocked = threading.Event()
self._unblocked.set()
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def get(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.get(self, *args, **kwargs)
def put(self, *args, **kwargs):
self._unblocked.wait()
return TypedQueue.put(self, *args, **kwargs)
def clear(self):
cleared = []
while True:
try:
cleared.append(TypedQueue.get(self, False))
TypedQueue.task_done(self)
except queue.Empty:
break
return cleared
class SendQueue(PrependableQueue):
def __init__(self, maxsize=0):
PrependableQueue.__init__(self, maxsize=maxsize)
self._unblocked = threading.Event()
self._unblocked.set()
self._resend_queue = PrependableQueue()
self._send_queue = PrependableQueue()
self._lookup = set()
self._resend_active = False
@property
def resend_active(self):
return self._resend_active
@resend_active.setter
def resend_active(self, resend_active):
with self.mutex:
self._resend_active = resend_active
def block(self):
self._unblocked.clear()
def unblock(self):
self._unblocked.set()
@contextlib.contextmanager
def blocked(self):
self.block()
try:
yield
finally:
self.unblock()
def prepend(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.prepend(self, (item, item_type, target), block=block, timeout=timeout)
def put(self, item, item_type=None, target=None, block=True, timeout=None):
self._unblocked.wait()
PrependableQueue.put(self, (item, item_type, target), block=block, timeout=timeout)
def get(self, block=True, timeout=None):
self._unblocked.wait()
item, _, _ = PrependableQueue.get(self, block=block, timeout=timeout)
return item
def clear(self):
cleared = []
while True:
try:
cleared.append(PrependableQueue.get(self, False))
PrependableQueue.task_done(self)
except queue.Empty:
break
return cleared
def _put(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.put(item)
else:
self._send_queue.put(item)
def _prepend(self, item):
_, item_type, target = item
if item_type is not None:
if item_type in self._lookup:
raise TypeAlreadyInQueue(item_type, "Type {} is already in queue".format(item_type))
else:
self._lookup.add(item_type)
if target == "resend":
self._resend_queue.prepend(item)
else:
self._send_queue.prepend(item)
def _get(self):
if self.resend_active:
item = self._resend_queue.get(block=False)
else:
try:
item = self._resend_queue.get(block=False)
except queue.Empty:
item = self._send_queue.get(block=False)
_, item_type, _ = item
if item_type is not None:
if item_type in self._lookup:
self._lookup.remove(item_type)
return item
def _qsize(self, len=len):
if self.resend_active:
return self._resend_queue.qsize()
else:
return self._resend_queue.qsize() + self._send_queue.qsize()
class QueueMarker(object):
def __init__(self, callback):
self.callback = callback
def run(self):
if callable(self.callback):
try:
self.callback()
except Exception:
logging.getLogger(__name__).exception("Error while running callback of QueueMarker")
class SendQueueMarker(QueueMarker):
pass
-37
View File
@@ -1,37 +0,0 @@
# -*- 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"
class Script(object):
def __init__(self, name, renderer, context=None):
if context is None:
context = dict()
self.name = name
self.renderer = renderer
self.context = context
def render(self, context=None):
if context is None:
context = dict()
render_context = dict(self.context)
render_context.update(context)
content = self.renderer(render_context)
if content is None:
return None
return content.split("\n")
class UnknownScript(Exception):
def __init__(self, name, *args, **kwargs):
self.name = name
class InvalidScript(Exception):
pass
-350
View File
@@ -1,350 +0,0 @@
# -*- 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"
from octoprint.comm.util.parameters import get_param_dict
import copy
import logging
import time
from octoprint.util import monotonic_time
from octoprint.util.listener import ListenerAware
from octoprint.plugin import plugin_manager
from octoprint.settings import SubSettings
_registry = dict()
def register_transports():
from .serialtransport import SerialTransport
from .sockettransport import TcpTransport, SerialOverTcpTransport
logger = logging.getLogger(__name__)
# stock transports
register_transport(SerialTransport)
register_transport(TcpTransport)
register_transport(SerialOverTcpTransport)
# more transports provided by plugins
hooks = plugin_manager().get_hooks("octoprint.comm.transport.register")
for name, hook in hooks.items():
try:
transports = hook()
for transport in transports:
try:
register_transport(transport)
except Exception:
logger.exception("Error while registering transport class {} for plugin {}".format(transport, name))
except Exception:
logger.exception("Error executing octoprint.comm.transport.register hook for plugin {}".format(name))
def register_transport(transport_class):
if not hasattr(transport_class, "key"):
raise ValueError("Transport class {} is missing key".format(transport_class))
_registry[transport_class.key] = transport_class
def lookup_transport(key):
return _registry.get(key)
def all_transports():
return _registry.values()
class Transport(ListenerAware):
name = None
key = None
message_integrity = False
@classmethod
def get_connection_options(cls):
return []
@classmethod
def get_settings_defaults(cls):
return dict()
def __init__(self, *args, **kwargs):
super(Transport, self).__init__()
self._logger = logging.getLogger(__name__)
self._state = TransportState.DISCONNECTED
self._args = dict()
self._printer_profile = kwargs.get("printer_profile")
self._plugin_manager = kwargs.get("plugin_manager")
self._event_bus = kwargs.get("event_bus")
self._settings = kwargs.get("settings")
if not isinstance(self._settings, TransportSettings):
self._settings = TransportSettings(self._settings, self)
def args(self):
return copy.deepcopy(self._args)
def set_current_args(self, **value):
self._args = copy.deepcopy(value)
@property
def state(self):
return self._state
@state.setter
def state(self, value):
old_state = self.state
self._state = value
self.notify_listeners("on_transport_log_message", self, "Transport state changed from '{}' to '{}'".format(old_state, value))
def connect(self, **params):
if self.state == TransportState.CONNECTED:
raise TransportAlreadyConnectedError("Already connected, disconnect first")
options = self.get_connection_options()
param_dict = get_param_dict(params, options)
self.create_connection(**param_dict)
self.state = TransportState.CONNECTED
self.notify_listeners("on_transport_connected", self)
def disconnect(self, error=None):
if self.state == TransportState.DISCONNECTED:
raise TransportNotConnectedError("Already disconnected")
success = self.drop_connection()
if not success and not error:
error = "Error disconnecting transport"
if error:
self.state = TransportState.DISCONNECTED_WITH_ERROR
self.notify_listeners("on_transport_log_message", self, error)
else:
self.state = TransportState.DISCONNECTED
self.notify_listeners("on_transport_disconnected", self, error=error)
def create_connection(self, *args, **kwargs):
return True
def drop_connection(self):
return True
def read(self, size=None, timeout=None):
data = self.do_read(size=size, timeout=timeout)
self.notify_listeners("on_transport_log_received_data", self, data)
return data
def write(self, data):
self.do_write(data)
self.notify_listeners("on_transport_log_sent_data", self, data)
@property
def in_waiting(self):
return 0
def do_read(self, size=None, timeout=None):
return b""
def do_write(self, data):
pass
def __str__(self):
return self.__class__.__name__
class TransportState(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
DISCONNECTED_WITH_ERROR = "disconnected_with_error"
class TransportSettings(SubSettings):
def __init__(self, settings, transport):
self.transport = transport.key
SubSettings.__init__(self, settings, ["comm", "transport", transport.key],
defaults=transport.get_settings_defaults())
class TransportNotConnectedError(Exception):
pass
class TransportAlreadyConnectedError(Exception):
pass
class TransportWrapper(ListenerAware):
unforwarded_handlers = []
"""Allows to explicitly disable certain transport listener handlers on sub classes."""
def __init__(self, transport):
ListenerAware.__init__(self)
self.transport = transport
self.transport.register_listener(self)
# make sure we forward any transport listener calls to our own registered listeners
def forward_handler(name):
def f(*args, **kwargs):
# replace references to self.transport with self
args = [self if arg == self.transport else arg for arg in args]
kwargs = dict((key, self if value == self.transport else value) for key, value in kwargs.items())
# forward
self.notify_listeners(name, *args, **kwargs)
return f
for handler in filter(lambda x: x.startswith("on_transport_"), dir(TransportListener)):
if handler not in self.__class__.unforwarded_handlers:
setattr(self, handler, forward_handler(handler))
def __getattr__(self, item):
return getattr(self.transport, item)
class SeparatorAwareTransportWrapper(TransportWrapper):
unforwarded_handlers = ["on_transport_log_received_data"]
"""We have read overwritten and hence send our own received_data notification."""
def __init__(self, transport, terminator):
TransportWrapper.__init__(self, transport)
self.terminator = terminator
self._buffered = bytearray()
def read(self, size=None, timeout=None):
start = monotonic_time()
termlen = len(self.terminator)
data = self._buffered
while True:
# make sure we always read everything that is waiting
data += bytearray(self.transport.read(self.transport.in_waiting))
# check for terminator, if it's there we have found our line
termpos = data.find(self.terminator)
if termpos >= 0:
# line: everything up to and incl. the terminator
line = data[:termpos + termlen]
# buffered: everything after the terminator
self._buffered = data[termpos + termlen:]
received = bytes(line)
self.notify_listeners("on_transport_log_received_data", self, received)
return received
# check if timeout expired
if timeout and monotonic_time() > start + timeout:
break
# if we arrive here we so far couldn't read a full line, wait for more data
c = self.transport.read(1)
if not c:
# EOF
break
# add to data and loop
data += c
self._buffered = data
raise TimeoutTransportException()
def __str__(self):
return "SeparatorAwareTransportWrapper({}, separator={})".format(self.transport, self.terminator)
class LineAwareTransportWrapper(SeparatorAwareTransportWrapper):
def __init__(self, transport):
SeparatorAwareTransportWrapper.__init__(self, transport, b"\n")
def __str__(self):
return "LineAwareTransportWrapper({})".format(self.transport)
class PushingTransportWrapper(TransportWrapper):
def __init__(self, transport, name=b"PushingTransportWrapper.receiver_loop", timeout=None):
super(PushingTransportWrapper, self).__init__(transport)
self.name = name
self.timeout = timeout
self._receiver_active = False
self._receiver_thread = None
@property
def active(self):
return self._receiver_active
def connect(self, **kwargs):
self.transport.connect(**kwargs)
import threading
self._receiver_active = True
self._receiver_thread = threading.Thread(target=self._receiver_loop, name=self.name)
self._receiver_thread.daemon = True
self._receiver_thread.start()
def disconnect(self):
self._receiver_active = False
self.transport.disconnect()
def wait(self):
self._receiver_thread.join()
def _receiver_loop(self):
while self._receiver_active:
try:
data = self.transport.read(timeout=self.timeout)
self.notify_listeners("on_transport_data_pushed", self, data)
except TimeoutTransportException as ex:
self.notify_listeners("on_transport_data_exception", self, ex)
except Exception:
if self._receiver_active:
raise
def __str__(self):
return "PushingTransportWrapper({})".format(self.transport)
class TransportListener(object):
def on_transport_connected(self, transport):
pass
def on_transport_disconnected(self, transport, error=None):
pass
def on_transport_log_sent_data(self, transport, data):
pass
def on_transport_log_received_data(self, transport, data):
pass
def on_transport_log_message(self, transport, data):
pass
class PushingTransportWrapperListener(object):
def on_transport_data_pushed(self, transport, data):
pass
def on_transport_data_exception(self, transport, exception):
pass
class TransportException(Exception):
pass
class TimeoutTransportException(TransportException):
pass
class EofTransportException(TransportException):
pass
@@ -1,206 +0,0 @@
# -*- 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"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper, PushingTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType, ChoiceType, SuggestionType, BooleanType, Value
import serial
import logging
class SerialTransport(Transport):
name = "Serial Connection"
key = "serial"
message_integrity = False
suggested_baudrates = [250000, 230400, 115200, 57600, 38400, 19200, 9600]
unix_port_patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/tty.usb*",
"/dev/cu.*", "/dev/cuaU*", "/dev/rfcomm*"]
max_write_passes = 5
@classmethod
def for_additional_ports_and_baudrates(cls, additional_ports, additional_baudrates):
patterns = SerialTransport.unix_port_patterns
if additional_ports:
patterns += additional_ports
baudrates = SerialTransport.suggested_baudrates
if additional_baudrates:
baudrates += additional_baudrates
return type(cls.__name__ + b"WithAdditionalPorts",
(cls,),
{b"unix_port_patterns": patterns,
b"suggested_baudrates": baudrates})
@classmethod
def get_connection_options(cls):
return [
SuggestionType("port", "Port", cls.get_available_serial_ports(), lambda value: Value(value)),
SuggestionType("baudrate", "Baudrate", cls.get_available_baudrates(), lambda value: Value(value), default=0),
IntegerType("write_timeout", "Write Timeout (sec)", min=1, default=10, advanced=True),
BooleanType("exclusive", "Exclusive access", default=True, advanced=True),
ChoiceType("parity", "Parity",
[Value(serial.PARITY_NONE, "none"),
Value(serial.PARITY_ODD, "odd"),
Value(serial.PARITY_EVEN, "even")],
default=serial.PARITY_NONE, advanced=True)
]
@classmethod
def get_available_serial_ports(cls):
import sys
if sys.platform == "win32":
# windows
from serial.tools.list_ports import comports
ports = comports()
else:
# posix
import glob
devices = [device
for pattern in cls.unix_port_patterns
for device in glob.glob(pattern)]
plat = sys.platform.lower()
if plat[:5] == "linux":
# linux
from serial.tools.list_ports_linux import SysFS
ports = [info
for info in [SysFS(d) for d in devices]
if info.subsystem != "platform"]
else:
# other posix systems
from serial.tools import list_ports_common
ports = [list_ports_common.ListPortInfo(d) for d in devices]
port_values = [Value(None, title="Auto detect")] + sorted([Value(port.device, title=port.description) for port in ports], key=lambda x: x.title)
return port_values
@classmethod
def get_available_baudrates(cls):
return [Value(0, title="Auto detect")] + \
sorted([Value(baudrate) for baudrate in cls.suggested_baudrates], key=lambda x: x.title, reverse=True)
def __init__(self, *args, **kwargs):
super(SerialTransport, self).__init__()
self.serial_factory = kwargs.get("serial_factory", None)
self._logger = logging.getLogger(__name__)
self._serial = None
self._closing = False
def create_connection(self, **kwargs):
factory = self.serial_factory
if self.serial_factory is None:
factory = self._default_serial_factory
self._closing = False
self._serial = factory(**kwargs)
self.set_current_args(**kwargs)
return True
def drop_connection(self):
error = False
if self._serial is not None:
self._closing = True
try:
if callable(getattr(self._serial, "cancel_read", None)):
self._serial.cancel_read()
except Exception:
self._logger.exception("Error while cancelling pending reads from the serial port")
try:
if callable(getattr(self._serial, "cancel_write", None)):
self._serial.cancel_write()
except Exception:
self._logger.exception("Error while cancelling pending writes to the serial port")
try:
self._serial.close()
except Exception:
self._logger.exception("Error while closing the serial port")
error = True
self._serial = None
return not error
def do_read(self, size=None, timeout=None):
return self._serial.read(size=size)
def do_write(self, data):
written = 0
passes = 0
def try_to_write(d):
result = self._serial.write(d)
if result is None or not isinstance(result, int):
# probably some plugin not returning the written bytes, assuming all of them
return len(data)
else:
return result
while written < len(data):
to_send = data[written:]
old_written = written
try:
written += try_to_write(to_send)
except serial.SerialTimeoutException:
self._logger.warn("Serial timeout while writing to serial port, trying again.")
try:
# second try
written += try_to_write(to_send)
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
except Exception:
if not self._closing:
message = "Unexpected error while writing to serial port"
self._logger.exception(message)
self.disconnect(error=message)
break
if old_written == written:
passes += 1
if passes > self.max_write_passes:
message = "Could not write anything to the serial port in {} tries, something appears to be " \
"wrong with the printer communication".format(self.max_write_passes)
self._logger.error(message)
self.disconnect(error=message)
break
@property
def in_waiting(self):
return getattr(self._serial, "in_waiting", 0)
def _default_serial_factory(self, **kwargs):
return serial.Serial(port=kwargs.get("port"),
baudrate=kwargs.get("baudrate"),
exclusive=kwargs.get("exclusive"),
parity=kwargs.get("parity"),
write_timeout=kwargs.get("write_timeout", 10) * 1000)
def __str__(self):
return "SerialTransport"
if __name__ == "__main__":
# list ports
ports = SerialTransport.get_available_serial_ports()
for port in ports:
print(port.title + ": " + port.value)
@@ -1,65 +0,0 @@
# -*- 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"
from octoprint.comm.transport import Transport, LineAwareTransportWrapper
from octoprint.comm.util.parameters import TextType, IntegerType
import socket
class TcpTransport(Transport):
name = "TCP Connection"
key = "tcpsocket"
message_integrity = True
@classmethod
def get_connection_options(cls):
return [
TextType("host", "Host"),
IntegerType("port", "Port", min=1, max=65535)
]
def __init__(self):
super(TcpTransport, self).__init__()
self._socket = None
def create_connection(self, host=None, port=None):
if host is None:
raise ValueError("host must not be None")
if port is None:
raise ValueError("port must not be None")
self._socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self._socket.connect((host, port))
self.set_current_args(host=host, port=port)
return True
def drop_connection(self):
try:
self._socket.close()
return True
except Exception:
self._logger.exception("Error closing socket")
return False
def do_read(self, size=None, timeout=None):
if size is None:
size = 16
return self._socket.recv(size)
def do_write(self, data):
self._socket.sendall(data)
def __str__(self):
return "TcpTransport"
class SerialOverTcpTransport(TcpTransport):
name = "Serial Connection over TCP"
key = "serialovertcpsocket"
message_integrity = False
View File
Whitespace-only changes.
-194
View File
@@ -1,194 +0,0 @@
# -*- 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"
from past.builtins import unicode
def get_param_dict(data, options):
options_by_name = dict((option.name, option) for option in options)
result = dict()
for key, value in data.items():
if not key in options_by_name:
continue
option = options_by_name[key]
result[key] = option.convert(value)
return result
class ParamType(object):
type = "generic"
def __init__(self, name, title, default=None, advanced=False, help=None):
self.name = name
self.title = title
self.default = default
self.advanced = advanced
self.help = help
def as_dict(self):
return dict(name=self.name,
title=self.title,
default=self.default,
advanced=self.advanced,
help=self.help,
type=self.type)
def convert(self, value):
return value
def __repr__(self):
return "{}(".format(self.__class__.__name__) \
+ ", ".join(["{}={!r}".format(key, value) for key, value in self.__dict__.items() if not key.startswith("_")]) + ")"
class TextType(ParamType):
type = "text"
def convert(self, value):
if isinstance(value, bytes):
value = value.decode("utf-8", "replace")
return value
class IntegerType(ParamType):
type = "integer"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = int(value)
except ValueError:
raise ValueError("value {!r} is not a valid integer".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class FloatType(ParamType):
type = "float"
def __init__(self, name, title, min=None, max=None, unit=None, **kwargs):
self.min = min
self.max = max
self.unit = unit
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(min=self.min,
max=self.max,
unit=self.unit))
return result
def convert(self, value):
try:
value = float(value)
except ValueError:
raise ValueError("value {!r} is not a valid float".format(value))
if self.min is not None and value < self.min:
raise ValueError("value {} is less than minimum valid value {}".format(value, self.min))
if self.max is not None and value > self.max:
raise ValueError("value {} is greater than maximum valid value {}".format(value, self.max))
return value
class BooleanType(ParamType):
type = "boolean"
def convert(self, value):
try:
value = bool(value)
except ValueError:
raise ValueError("value {!r} is not a valid boolean".format(value))
return value
class ChoiceType(ParamType):
type = "choice"
def __init__(self, name, title, choices, **kwargs):
self.choices = choices
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(choices=list(map(lambda x: x.as_dict(), self.choices))))
return result
class SmallChoiceType(ChoiceType):
type = "smallchoice"
class SuggestionType(ParamType):
type = "suggestion"
def __init__(self, name, title, suggestions, factory, **kwargs):
self.suggestions = suggestions
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def as_dict(self):
result = ParamType.as_dict(self)
result.update(dict(suggestions=list(map(lambda x: x.as_dict(), self.suggestions))))
return result
class ListType(ParamType):
type = "list"
def __init__(self, name, title, factory, **kwargs):
self.factory = factory
ParamType.__init__(self, name, title, **kwargs)
def convert(self, value):
if isinstance(value, unicode):
items = map(unicode.strip, value.split(","))
elif isinstance(value, list):
items = value
else:
raise ValueError("value {!r} must be either a comma-separated string or a list".format(value))
return list(map(self.factory, items))
class ParamGroup(ParamType):
type = "group"
def __init__(self, name, title, params, help=None, advanced=False):
ParamType.__init__(self, name, title, help=help, advanced=advanced)
self.params = params
def as_dict(self):
result = ParamType.as_dict(self)
result["params"] = [x.as_dict() for x in self.params]
return result
def convert(self, value):
if not isinstance(value, dict):
raise ValueError("value {!r} must be a dict".format(value))
return dict((k, v.convert()) for k, v in value.items())
class Value(object):
def __init__(self, value, title=None, help=None):
self.value = value
self.title = title if title else value
self.help = help
def as_dict(self):
return dict(value=self.value,
title=self.title,
help=self.help)
+4 -8
View File
@@ -47,6 +47,10 @@ class Events(object):
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
@@ -227,14 +231,6 @@ class EventManager(object):
q.put((event, payload))
if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables":
# when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode"
# TODO v1.4.0 Remove again
import copy
legacy_payload = copy.deepcopy(payload)
legacy_payload["type"] = "gcode"
q.put((event, legacy_payload))
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
+34 -27
View File
@@ -16,11 +16,12 @@ from octoprint.events import eventManager, Events
from .destinations import FileDestinations
from .analysis import QueueEntry, AnalysisQueue
from .storage import LocalFileStorage
from .util import AbstractFileWrapper, StreamWrapper, DiskFileWrapper
from octoprint.util import get_fully_qualified_classname as fqcn
from collections import namedtuple
# noinspection PyCompatibility
from past.builtins import basestring
ContentTypeMapping = namedtuple("ContentTypeMapping", "extensions, content_type")
@@ -224,6 +225,7 @@ class FileManager(object):
import octoprint.settings
self._recovery_file = os.path.join(octoprint.settings.settings().getBaseFolder("data"), "print_recovery_data.yaml")
self._analyzeGcode = octoprint.settings.settings().get(["gcodeAnalysis", "runAt"])
def initialize(self, process_backlog=False):
self.reload_plugins()
@@ -231,6 +233,10 @@ class FileManager(object):
self.process_backlog()
def process_backlog(self):
# only check for a backlog if gcodeAnalysis is 'idle' or 'always'
if self._analyzeGcode == "never":
return
def worker():
self._logger.info("Adding backlog items from all storage types to analysis queue...".format(**locals()))
for storage_type, storage_manager in self._storage_managers.items():
@@ -330,16 +336,18 @@ class FileManager(object):
printer_profile_id, callback, callback_args, _error=None, _cancelled=False, _analysis=None):
try:
if _error:
eventManager().fire(Events.SLICING_FAILED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
reason=_error))
eventManager().fire(Events.SLICING_FAILED, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
reason=_error))
elif _cancelled:
eventManager().fire(Events.SLICING_CANCELLED, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location))
eventManager().fire(Events.SLICING_CANCELLED, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location))
else:
source_meta = self.get_metadata(source_location, source_path)
hash = source_meta.get("hash", "n/a")
@@ -357,11 +365,12 @@ class FileManager(object):
printer_profile=printer_profile, analysis=_analysis)
end_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_DONE, dict(stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
time=end_time - start_time))
eventManager().fire(Events.SLICING_DONE, dict(slicer=slicer_name,
stl=source_path,
stl_location=source_location,
gcode=dest_path,
gcode_location=dest_location,
time=end_time - start_time))
if callback is not None:
if callback_args is None:
@@ -382,7 +391,8 @@ class FileManager(object):
slicer = self._slicing_manager.get_slicer(slicer_name)
start_time = octoprint.util.monotonic_time()
eventManager().fire(Events.SLICING_STARTED, {"stl": source_path,
eventManager().fire(Events.SLICING_STARTED, {"slicer": slicer_name,
"stl": source_path,
"stl_location": source_location,
"gcode": dest_path,
"gcode_location": dest_location,
@@ -428,7 +438,8 @@ class FileManager(object):
try:
callback.sendSlicingProgress(slicer, source_location, source_path, dest_location, dest_path, progress_int)
except Exception:
self._logger.exception("Exception while pushing slicing progress")
self._logger.exception("Exception while pushing slicing progress",
extra=dict(callback=fqcn(callback)))
if progress_int:
def call_plugins(slicer, source_location, source_path, dest_location, dest_path, progress):
@@ -602,9 +613,6 @@ class FileManager(object):
name=dst_name))
eventManager().fire(Events.UPDATED_FILES, dict(type="printables"))
def create_print_job(self, destination, path, user=None):
return self._storage(destination).create_print_job(path, user=user)
def has_analysis(self, destination, path):
return self._storage(destination).has_analysis(path)
@@ -619,13 +627,10 @@ class FileManager(object):
def log_print(self, destination, path, timestamp, print_time, success, printer_profile):
try:
try:
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
except NotImplementedError:
pass
if success:
self._storage(destination).add_history(path, dict(timestamp=timestamp, printTime=print_time, success=success, printerProfile=printer_profile))
else:
self._storage(destination).add_history(path, dict(timestamp=timestamp, success=success, printerProfile=printer_profile))
eventManager().fire(Events.METADATA_STATISTICS_UPDATED, dict(storage=destination, path=path))
except NoSuchStorage:
# if there's no storage configured where to log the print, we'll just not log it
@@ -663,6 +668,8 @@ class FileManager(object):
try:
with io.open(self._recovery_file, 'rt', encoding='utf-8') as f:
data = yaml.safe_load(f)
if not isinstance(data, dict) or not all(map(lambda x: x in data, ("origin", "path", "pos", "date"))):
raise ValueError("Invalid recovery data structure")
return data
except Exception:
self._logger.exception("Could not read recovery data from file {}".format(self._recovery_file))
+12 -10
View File
@@ -19,6 +19,7 @@ import time
from octoprint.events import Events, eventManager
from octoprint.settings import settings
from octoprint.util import monotonic_time
from octoprint.util import get_fully_qualified_classname as fqcn
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
@@ -109,14 +110,15 @@ class AnalysisQueue(object):
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
callback(entry, result)
try:
callback(entry, result)
except:
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
extra=dict(callback=fqcn(callback)))
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
# TODO: deprecated, remove in a future release
"file": entry.path})
"result": result})
class AbstractAnalysisQueue(object):
"""
@@ -174,7 +176,10 @@ class AbstractAnalysisQueue(object):
(False, default)
"""
if high_priority:
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
return
elif high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
else:
@@ -255,10 +260,7 @@ class AbstractAnalysisQueue(object):
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
# TODO deprecated, remove in 1.4.0
"file": entry.path})
"type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -20,7 +21,6 @@ except ImportError:
from octoprint.util import atomic_write
from contextlib import contextmanager
# noinspection PyCompatibility
from past.builtins import basestring
from emoji import demojize
@@ -30,10 +30,417 @@ import octoprint.filemanager
from octoprint.util import is_hidden_path, to_unicode, to_bytes
from . import Storage, StorageError
class StorageInterface(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
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, 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()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
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 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):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class LocalFileStorage(Storage):
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
class LocalFileStorage(StorageInterface):
"""
The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk.
@@ -59,7 +466,7 @@ class LocalFileStorage(Storage):
text = demojize(text, delimiters=("", ""))
return cls._SLUGIFY(text)
def __init__(self, basefolder, create=False, key="local"):
def __init__(self, basefolder, create=False):
"""
Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder
if necessary and ``create`` is set to ``True``.
@@ -442,17 +849,6 @@ class LocalFileStorage(Storage):
metadata = self.get_metadata(path)
return "analysis" in metadata
def create_print_job(self, path, user=None):
from octoprint.comm.job import LocalGcodeFilePrintjob
return LocalGcodeFilePrintjob(self.path_on_disk(path),
"local",
self.path_in_storage(path),
name=self.path_in_storage(path),
user=user,
event_data=dict(path=path,
name=self.split_path(path)[1],
origin="local"))
def get_metadata(self, path):
path, name = self.sanitize(path)
return self._get_metadata_entry(path, name)
@@ -1,457 +0,0 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
try:
from os import scandir, walk
except ImportError:
from scandir import scandir, walk
class Storage(object):
"""
Interface of storage adapters for OctoPrint.
"""
@property
def analysis_backlog(self):
"""
Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`.
The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget
to recurse into folders if your storage adapter supports those.
:return: an iterator yielding all un-analysed files in the storage
"""
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def analysis_backlog_for_path(self, path=None):
# empty generator pattern, yield is intentionally unreachable
return
# noinspection PyUnreachableCode
yield
def last_modified(self, path=None, recursive=False):
"""
Get the last modification date of the specified ``path`` or ``path``'s subtree.
Args:
path (str or None): Path for which to determine the subtree's last modification date. If left out or
set to None, defatuls to storage root.
recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or
the whole ``path``'s subtree (True).
Returns: (float) The last modification date of the indicated subtree
"""
raise NotImplementedError()
def file_in_path(self, path, filepath):
"""
Returns whether the file indicated by ``file`` is inside ``path`` or not.
:param string path: the path to check
:param string filepath: path to the file
:return: ``True`` if the file is inside the path, ``False`` otherwise
"""
return NotImplementedError()
def file_exists(self, path):
"""
Returns whether the file indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the file exists, ``False`` otherwise
"""
raise NotImplementedError()
def folder_exists(self, path):
"""
Returns whether the folder indicated by ``path`` exists or not.
:param string path: the path to check for existence
:return: ``True`` if the folder exists, ``False`` otherwise
"""
raise NotImplementedError()
def list_files(self, path=None, filter=None, recursive=True):
"""
List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into
subfolders.
An optional filter function can be supplied which will be called with a file name and file data and which has
to return True if the file is to be included in the result or False if not.
The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes
will contain their metadata here, folder nodes will contain their contained files and folders. Example::
{
"some_folder": {
"name": "some_folder",
"path": "some_folder",
"type": "folder",
"children": {
"some_sub_folder": {
"name": "some_sub_folder",
"path": "some_folder/some_sub_folder",
"type": "folder",
"typePath": ["folder"],
"children": { ... }
},
"some_file.gcode": {
"name": "some_file.gcode",
"path": "some_folder/some_file.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [ ... ],
...
},
...
}
"test.gcode": {
"name": "test.gcode",
"path": "test.gcode",
"type": "machinecode",
"typePath": ["machinecode", "gcode"],
"hash": "<sha1 hash>",
"links": [...],
...
},
"test.stl": {
"name": "test.stl",
"path": "test.stl",
"type": "model",
"typePath": ["model", "stl"],
"hash": "<sha1 hash>",
"links": [...],
...
},
...
}
:param string path: base path from which to recursively list all files, optional, if not supplied listing will start
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, 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()
def add_folder(self, path, ignore_existing=True, display=None):
"""
Adds a folder as ``path``
The ``path`` will be sanitized.
:param string path: the path of the new folder
:param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists
:param unicode display: display name of the folder
:return: the sanitized name of the new folder to be used for future references to the folder
"""
raise NotImplementedError()
def remove_folder(self, path, recursive=True):
"""
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 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):
"""
Copies the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the path in the storage to the copy of the folder
"""
raise NotImplementedError()
def move_folder(self, source, destination):
"""
Moves the folder ``source`` to ``destination``
:param string source: path to the source folder
:param string destination: path to destination
:return: the new path in the storage to the folder
"""
raise NotImplementedError()
def add_file(self, path, file_object, printer_profile=None, links=None, allow_overwrite=False, display=None):
"""
Adds the file ``file_object`` as ``path``
:param string path: the file's new path, will be sanitized
:param object file_object: a file object that provides a ``save`` method which will be called with the destination path
where the object should then store its contents
:param object printer_profile: the printer profile associated with this file (if any)
:param list links: any links to add with the file
:param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file
and its metadata will just be silently overwritten
:param unicode display: display name of the file
:return: the sanitized name of the file to be used for future references to it
"""
raise NotImplementedError()
def remove_file(self, path):
"""
Removes the file at ``path``
Will also take care of deleting the corresponding entries
in the metadata and deleting all links pointing to the file.
:param string path: path of the file to remove
"""
raise NotImplementedError()
def copy_file(self, source, destination):
"""
Copies the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the path in the storage to the copy of the file
"""
raise NotImplementedError()
def move_file(self, source, destination):
"""
Moves the file ``source`` to ``destination``
:param string source: path to the source file
:param string destination: path to destination
:return: the new path in the storage to the file
"""
raise NotImplementedError()
def has_analysis(self, path):
"""
Returns whether the file at path has been analysed yet
:param path: virtual path to the file for which to retrieve the metadata
"""
raise NotImplementedError()
def create_print_job(self, path, user=None):
"""
Retrieves the :class:`~octoprint.job.PrintJob` instance
to use for printing ``path``.
"""
raise NotImplementedError()
def get_metadata(self, path):
"""
Retrieves the metadata for the file ``path``.
:param path: virtual path to the file for which to retrieve the metadata
:return: the metadata associated with the file
"""
raise NotImplementedError()
def add_link(self, path, rel, data):
"""
Adds a link of relation ``rel`` to file ``path`` with the given ``data``.
The following relation types are currently supported:
* ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name``
and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the
current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode``
referring to ``name`` and its hash will also be added to the linked ``model`` file
* ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected
additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved
against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse
link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file.
* ``web``: adds a location on the web associated with this file (e.g. a website where to download a model),
expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved``
attribute describing when the content was retrieved
Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying
as machine code will be refused.
:param path: path of the file for which to add a link
:param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to add
"""
raise NotImplementedError()
def remove_link(self, path, rel, data):
"""
Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``.
:param path: path of the file from which to remove the link
:param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported)
:param data: additional data of the link to remove, must match existing link
"""
raise NotImplementedError()
def add_history(self, path, data):
"""
Adds a history entry for the given ``path``.
:param path: path of the file for which to add the history entry
:param data: history entry
"""
raise NotImplementedError()
def update_history(self, path, index, data):
"""
Updates the history entry for ``path`` at ``index``.
:param path: path of the file for which to update the history entry
:param index: index
:param data: history entry
"""
raise NotImplementedError()
def remove_history(self, path, index):
"""
Removes the history entry for ``path`` at ``index``.
:param path: path of the file for which to remove the history entry
:param index: index
"""
raise NotImplementedError()
def set_additional_metadata(self, path, key, data, overwrite=False, merge=False):
"""
Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``.
If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten.
If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries,
the two dictionaries will be merged recursively.
:param path: the virtual path to the file for which to add additional metadata
:param key: key of metadata to add
:param data: metadata to add
:param overwrite: if True and ``key`` already exists, it will be overwritten
:param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they
will be merged
"""
raise NotImplementedError()
def remove_additional_metadata(self, path, key):
"""
Removes additional metadata under ``key`` for ``name`` on ``path``
:param path: the virtual path to the file for which to remove the metadata under ``key``
:param key: the key to remove
"""
raise NotImplementedError()
def canonicalize(self, path):
"""
Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying
implementation must separate those if necessary.
By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care
of stripping any invalid characters.
Args:
path: the path to canonicalize
Returns:
a 2-tuple containing the canonicalized path and file name
"""
return self.sanitize(path)
def sanitize(self, path):
"""
Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both
folder and file name, the underlying implementation must separate those if necessary and sanitize individually.
:param string path: the path to sanitize
:return: a 2-tuple containing the sanitized path and file name
"""
raise NotImplementedError()
def sanitize_path(self, path):
"""
Sanitizes the given folder-only ``path``, stripping it of all invalid characters.
:param string path: the path to sanitize
:return: the sanitized path
"""
raise NotImplementedError()
def sanitize_name(self, name):
"""
Sanitizes the given file ``name``, stripping it of all invalid characters.
:param string name: the file name to sanitize
:return: the sanitized name
"""
raise NotImplementedError()
def split_path(self, path):
"""
Split ``path`` into base directory and file name.
:param path: the path to split
:return: a tuple (base directory, file name)
"""
raise NotImplementedError()
def join_path(self, *path):
"""
Join path elements together
:param path: path elements to join
:return: joined representation of the path to be usable as fully qualified path for further operations
"""
raise NotImplementedError()
def path_on_disk(self, path):
"""
Retrieves the path on disk for ``path``.
Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should
raise an :class:`io.UnsupportedOperation`
Opposite of :func:`path_in_storage`.
:param string path: the virtual path for which to retrieve the path on disk
:return: the path on disk to ``path``
"""
raise NotImplementedError()
def path_in_storage(self, path):
"""
Retrieves the equivalent in the storage adapter for ``path``.
Opposite of :func:`path_on_disk`.
:param string path: the path for which to retrieve the storage path
:return: the path in storage to ``path``
"""
raise NotImplementedError()
class StorageError(Exception):
UNKNOWN = "unknown"
INVALID_DIRECTORY = "invalid_directory"
INVALID_FILE = "invalid_file"
INVALID_SOURCE = "invalid_source"
INVALID_DESTINATION = "invalid_destination"
DOES_NOT_EXIST = "does_not_exist"
ALREADY_EXISTS = "already_exists"
SOURCE_EQUALS_DESTINATION = "source_equals_destination"
NOT_EMPTY = "not_empty"
def __init__(self, message, code=None, cause=None):
BaseException.__init__(self)
self.message = message
self.cause = cause
if code is None:
code = StorageError.UNKNOWN
self.code = code
@@ -1,14 +0,0 @@
# 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"
from . import Storage, StorageError
class PrinterSDStorage(Storage):
def create_print_job(self, path, user=None):
from octoprint.comm.job import SDFilePrintjob
return SDFilePrintjob("/" + path, user=user)
+8 -7
View File
@@ -62,23 +62,23 @@ class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
class SerialLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
do_rollover = dict()
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, logger):
cls.do_rollover[logger] = True
def on_open_connection(cls):
cls.do_rollover = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CommunicationLogHandler, self).__init__(*args, **kwargs)
super(SerialLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover.pop(record.name, False)
return self.do_rollover
def getFilesToDelete(self):
"""
@@ -107,6 +107,8 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
os.remove(path)
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
@@ -123,7 +125,6 @@ class CommunicationLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFil
if not self.delay:
self.stream = self._open()
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
+121 -8
View File
@@ -23,7 +23,7 @@ import os
import logging
import threading
from octoprint.settings import settings as s, SubSettings
from octoprint.settings import settings as s
from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin)
from octoprint.plugin.types import OctoPrintPlugin, SettingsPlugin
from octoprint.plugin.types import * # noqa: F403 ## used by multiple other modules
@@ -230,7 +230,7 @@ def call_plugin(types, method, args=None, kwargs=None, callback=None, error_call
error_callback(plugin._identifier, plugin, exc)
class PluginSettings(SubSettings):
class PluginSettings(object):
"""
The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings.
@@ -315,15 +315,78 @@ class PluginSettings(SubSettings):
"""
def __init__(self, settings, plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None):
self.settings = settings
self.plugin_key = plugin_key
SubSettings.__init__(self, settings, ["plugins", plugin_key],
defaults=defaults,
get_preprocessors=get_preprocessors,
set_preprocessors=set_preprocessors)
if self.defaults is not None:
if defaults is not None:
self.defaults = dict(plugins=dict())
self.defaults["plugins"][plugin_key] = defaults
self.defaults["plugins"][plugin_key]["_config_version"] = None
else:
self.defaults = None
if get_preprocessors is None:
get_preprocessors = dict()
self.get_preprocessors = dict(plugins=dict())
self.get_preprocessors["plugins"][plugin_key] = get_preprocessors
if set_preprocessors is None:
set_preprocessors = dict()
self.set_preprocessors = dict(plugins=dict())
self.set_preprocessors["plugins"][plugin_key] = set_preprocessors
def prefix_path_in_args(args, index=0):
result = []
if index == 0:
result.append(self._prefix_path(args[0]))
result.extend(args[1:])
else:
args_before = args[:index - 1]
args_after = args[index + 1:]
result.extend(args_before)
result.append(self._prefix_path(args[index]))
result.extend(args_after)
return result
def add_getter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.get_preprocessors)
return kwargs
def add_setter_kwargs(kwargs):
if not "defaults" in kwargs and self.defaults is not None:
kwargs.update(defaults=self.defaults)
if not "preprocessors" in kwargs:
kwargs.update(preprocessors=self.set_preprocessors)
return kwargs
self.access_methods = dict(
has =("has", prefix_path_in_args, add_getter_kwargs),
get =("get", prefix_path_in_args, add_getter_kwargs),
get_int =("getInt", prefix_path_in_args, add_getter_kwargs),
get_float =("getFloat", prefix_path_in_args, add_getter_kwargs),
get_boolean=("getBoolean", prefix_path_in_args, add_getter_kwargs),
set =("set", prefix_path_in_args, add_setter_kwargs),
set_int =("setInt", prefix_path_in_args, add_setter_kwargs),
set_float =("setFloat", prefix_path_in_args, add_setter_kwargs),
set_boolean=("setBoolean", prefix_path_in_args, add_setter_kwargs),
remove =("remove", prefix_path_in_args, lambda x: x)
)
self.deprecated_access_methods = dict(
getInt ="get_int",
getFloat ="get_float",
getBoolean="get_boolean",
setInt ="set_int",
setFloat ="set_float",
setBoolean="set_boolean"
)
def _prefix_path(self, path=None):
if path is None:
path = list()
return ['plugins', self.plugin_key] + path
def global_has(self, path, **kwargs):
return self.settings.has(path, **kwargs)
@@ -415,3 +478,53 @@ class PluginSettings(SubSettings):
filename += ".log"
return os.path.join(self.settings.getBaseFolder("logs"), filename)
@deprecated("PluginSettings.get_plugin_data_folder has been replaced by OctoPrintPlugin.get_plugin_data_folder",
includedoc="Replaced by :func:`~octoprint.plugin.types.OctoPrintPlugin.get_plugin_data_folder`",
since="1.2.0")
def get_plugin_data_folder(self):
path = os.path.join(self.settings.getBaseFolder("data"), self.plugin_key)
if not os.path.isdir(path):
os.makedirs(path)
return path
def get_all_data(self, **kwargs):
merged = kwargs.get("merged", True)
asdict = kwargs.get("asdict", True)
defaults = kwargs.get("defaults", self.defaults)
preprocessors = kwargs.get("preprocessors", self.get_preprocessors)
kwargs.update(dict(
merged=merged,
asdict=asdict,
defaults=defaults,
preprocessors=preprocessors
))
return self.settings.get(self._prefix_path(), **kwargs)
def clean_all_data(self):
self.settings.remove(self._prefix_path())
def __getattr__(self, item):
all_access_methods = list(self.access_methods.keys()) + list(self.deprecated_access_methods.keys())
if item in all_access_methods:
decorator = None
if item in self.deprecated_access_methods:
new = self.deprecated_access_methods[item]
decorator = deprecated("{old} has been renamed to {new}".format(old=item, new=new), stacklevel=2)
item = new
settings_name, args_mapper, kwargs_mapper = self.access_methods[item]
if hasattr(self.settings, settings_name) and callable(getattr(self.settings, settings_name)):
orig_func = getattr(self.settings, settings_name)
if decorator is not None:
orig_func = decorator(orig_func)
def _func(*args, **kwargs):
return orig_func(*args_mapper(args), **kwargs_mapper(kwargs))
_func.__name__ = to_native_str(item)
_func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None
return _func
return getattr(self.settings, item)
+4 -4
View File
@@ -39,7 +39,7 @@ import pkginfo
from past.builtins import unicode
from octoprint.util import to_unicode
from octoprint.util import to_unicode, sv
from octoprint.util.version import is_python_compatible, get_python_version_string
try:
@@ -447,7 +447,7 @@ class PluginInfo(object):
@property
def hooks(self):
"""
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defiend in
Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in
:attr:`attr_hooks` if available, otherwise an empty dictionary is returned.
Returns:
@@ -1585,7 +1585,7 @@ class PluginManager(object):
sorting_value = None
plugin_info = self.get_plugin_info(impl[0], require_enabled=False)
return sorting_value is None, sorting_value, not plugin_info.bundled if plugin_info else True, impl[0]
return sorting_value is None, sv(sorting_value), not plugin_info.bundled if plugin_info else True, sv(impl[0])
return [impl[1] for impl in sorted(result, key=sort_func)]
@@ -1672,7 +1672,7 @@ class PluginManager(object):
def _sort_hooks(self, hook):
self._plugin_hooks[hook] = sorted(self._plugin_hooks[hook],
key=lambda x: (x[0] is None, x[0], x[1], x[2]))
key=lambda x: (x[0] is None, sv(x[0]), sv(x[1]), sv(x[2])))
def _get_callback_and_order(self, hook):
if callable(hook):
@@ -82,6 +82,8 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
#~ SettingsPlugin
@@ -218,15 +220,18 @@ class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
return
self._close_prompt()
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)])
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)])
else:
self._printer.commands(["{command} S{choice}".format(command=self._command,
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")
" confirmation or selection prompts in OctoPrint")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
@@ -5,7 +5,17 @@ $(function() {
self.loginState = parameters[0];
self.access = parameters[1];
self._modal = undefined;
self.modal = ko.observable(undefined);
self.text = ko.observable();
self.buttons = ko.observableArray([]);
self.active = ko.pureComputed(function() {
return self.text() !== undefined;
});
self.visible = ko.pureComputed(function() {
return self.modal() !== undefined;
});
self.requestData = function() {
if (!self.loginState.hasPermission(self.access.permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT)) return;
@@ -16,26 +26,35 @@ $(function() {
self.fromResponse = function(data) {
if (data.hasOwnProperty("text") && data.hasOwnProperty("choices")) {
self._showPrompt(data.text, data.choices);
self.text(data.text);
self.buttons(data.choices);
self.showPrompt();
} else {
self.text(undefined);
self.buttons([]);
}
};
self._showPrompt = function(text, buttons) {
self.showPrompt = function() {
var text = self.text();
var buttons = self.buttons();
var opts = {
title: gettext("Message from your printer"),
message: text,
selections: buttons,
maycancel: true, // see #3171
onselect: function(index) {
if (index > -1) {
self._select(index);
}
},
onclose: function() {
self._modal = undefined;
self.modal(undefined);
}
};
self._modal = showSelectionDialog(opts)
self.modal(showSelectionDialog(opts));
};
self._select = function(index) {
@@ -43,8 +62,9 @@ $(function() {
};
self._closePrompt = function() {
if (self._modal) {
self._modal.modal("hide");
var modal = self.modal();
if (modal) {
modal.modal("hide");
}
};
@@ -60,10 +80,14 @@ $(function() {
switch (data.action) {
case "show": {
self._showPrompt(data.text, data.choices);
self.text(data.text);
self.buttons(data.choices);
self.showPrompt();
break;
}
case "close": {
self.text(undefined);
self.buttons([]);
self._closePrompt();
break;
}
@@ -74,6 +98,7 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: ActionCommandPromptViewModel,
dependencies: ["loginStateViewModel", "accessViewModel"]
dependencies: ["loginStateViewModel", "accessViewModel"],
elements: ["#navbar_plugin_action_command_prompt"]
});
});
@@ -0,0 +1,3 @@
<a id="navbar_show_prompt" class="pull-right" style="display: none" href="javascript:void(0)" data-bind="click: function() { showPrompt(); }, visible: active() && !visible()" title="{{ _('Message from your printer')|edq }}">
<i class="fa fa-commenting-o"></i>
</a>
@@ -1,3 +1,3 @@
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements') }}">
<a id="navbar_show_announcements" class="pull-right" href="javascript:void(0)" data-bind="click: function() { showAnnouncementDialog(); }" title="{{ _('Announcements')|edq }}">
<i class="fa" data-bind="css: {'fa-bell-o': !unread(), 'fa-bell': unread()}"></i>
</a>
+23 -4
View File
@@ -7,7 +7,7 @@ import os
import yaml
import io
import time
from binascii import hexlify
import uuid
from collections import defaultdict
from flask_babel import gettext
@@ -45,6 +45,12 @@ class PendingDecision(object):
user_id=self.user_id,
user_token=self.user_token)
def __repr__(self):
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
self.app_token,
self.user_id,
self.user_token)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
@@ -56,6 +62,11 @@ class ReadyDecision(object):
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
def __repr__(self):
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
self.app_token,
self.user_id)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
@@ -76,6 +87,11 @@ class ActiveKey(object):
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
self.api_key,
self.user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
@@ -135,12 +151,15 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
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:
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
@@ -362,7 +381,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.findUser(userid=user_id)
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
@@ -380,7 +399,7 @@ class AppKeysPlugin(octoprint.plugin.AssetPlugin,
return result
def _generate_key(self):
return hexlify(os.urandom(16))
return ''.join('%02X' % z for z in bytes(uuid.uuid4().bytes))
def _load_keys(self):
with self._keys_lock:
@@ -52,7 +52,7 @@ $(function() {
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
};
@@ -68,7 +68,7 @@ $(function() {
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 = _.sprintf(message, {app: _.escape(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"),
@@ -210,7 +210,7 @@ $(function() {
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: key}),
showConfirmationDialog(_.sprintf(gettext("You are about to revoke the application key \"%(key)s\"."), {key: _.escape(key)}),
perform);
};
@@ -258,11 +258,11 @@ $(function() {
handler = function(key) {
return OctoPrint.plugins.appkeys.revokeKey(key)
.done(function() {
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: key}), true);
deferred.notify(_.sprintf(gettext("Revoked %(key)s..."), {key: _.escape(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});
var short = _.sprintf(gettext("Revocation of %(key)s failed, continuing..."), {key: _.escape(key)});
var long = _.sprintf(gettext("Deletion of %(key)s failed: %(error)s"), {key: _.escape(key), error: _.escape(jqXHR.responseText)});
deferred.notify(short, long, false);
});
};
@@ -40,8 +40,8 @@
<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>
<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')|edq }}" 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')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key, $data.user_id) }"></a></td>
</tr>
</tbody>
</table>
@@ -13,8 +13,8 @@
</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>
<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')|edq }}" 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')|edq }}" class="fa fa-trash-o" data-bind="click: function() { $parent.revokeKey($data.api_key) }"></a></td>
</tr>
</tbody>
</table>
+2
View File
@@ -633,6 +633,8 @@ class BackupPlugin(octoprint.plugin.SettingsPlugin,
try:
if exclude is None:
exclude = []
if not isinstance(exclude, list):
exclude = list(exclude)
if "timelapse" in exclude:
exclude.append("timelapse_tmp")
@@ -85,7 +85,7 @@ $(function() {
self.requestData();
});
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: backup}),
showConfirmationDialog(_.sprintf(gettext("You are about to delete backup file \"%(name)s\"."), {name: _.escape(backup)}),
perform);
};
@@ -101,7 +101,7 @@ $(function() {
OctoPrint.plugins.backup.restoreBackup(backup);
};
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: backup}),
showConfirmationDialog(_.sprintf(gettext("You are about to restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(backup)}),
perform);
};
@@ -117,7 +117,7 @@ $(function() {
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()}),
showConfirmationDialog(_.sprintf(gettext("You are about to upload and restore the backup file \"%(name)s\". This cannot be undone."), {name: _.escape(self.backupUploadName())}),
perform);
};
@@ -182,7 +182,7 @@ $(function() {
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}),
text: _.sprintf(gettext("OctoPrint could not create your backup. Please consult <code>octoprint.log</code> for details. Error: %(error)s"), {error: _.escape(data.error)}),
type: "error",
hide: false
});
@@ -197,16 +197,16 @@ $(function() {
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") {
} else if (data.type === "installing_plugin") {
self.loglines.push({line: " ", stream: "message"});
self.loglines.push({
line: _.sprintf(gettext("Installing plugin \"%(plugin)s}\"..."), {plugin: data.plugin.name}),
line: _.sprintf(gettext("Installing plugin \"%(plugin)s\"..."), {plugin: _.escape(data.plugin)}),
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}),
line: _.sprintf(gettext("Cannot install plugin \"%(plugin)s\" due to it being incompatible to this OctoPrint version and/or underlying operating system"), {plugin: _.escape(data.plugin.key)}),
stream: "stderr"
});
} else if (data.type === "unknown_plugins") {
@@ -245,11 +245,11 @@ $(function() {
handler = function(filename) {
return OctoPrint.plugins.backup.deleteBackup(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(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});
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
deferred.notify(short, long, false);
});
};
@@ -46,7 +46,7 @@
<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>
<td class="settings_plugin_backup_actions"><a href="javascript:void(0)" title="{{ _('Delete')|edq }}" 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')|edq }}" 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')|edq }}" 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>
@@ -29,7 +29,7 @@
<p>{% trans %}
Finally, please decide on whether to enable or disable the connectivity check. You may change the configuration at
any time to a later date through Settings > Server right from within OctoPrint.
any time through Settings > Server right from within OctoPrint.
{% endtrans %}</p>
<div class="row-fluid">
+1 -1
View File
@@ -212,7 +212,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin,
def zeroconf_unregister(self, reg_type, port=None):
"""
Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
Unregisters a previously registered Zeroconf/Bonjour/Avahi service identified by service and port.
:param reg_type: the type of the service to be unregistered
:param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given
@@ -7,13 +7,14 @@ __copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms
import octoprint.plugin
import logging
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version
from flask import jsonify
from flask_babel import gettext
SENTRY_URL_SERVER = "https://4069187705ab4e76921eb19db2e9ccbb@sentry.io/1373987"
SENTRY_URL_COREUI = "https://a4ab48f27daf4c129392b78be15412b8@sentry.io/1374096"
SENTRY_URL_SERVER = "https://bcd62166a2b145aa9818947bfb76706f@sentry.io/1373987"
SENTRY_URL_COREUI = "https://217a5d75940b443eaaec347bb30c128d@sentry.io/1374096"
SETTINGS_DEFAULTS = dict(enabled=False,
enabled_unreleased=False,
@@ -29,19 +30,24 @@ import tornado.websocket
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# isp errors during port auto detection in octoprint.util.comm
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin: logger == "octoprint.util.comm"),
(octoprint.util.avr_isp.ispBase.IspError, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."))
]
try:
@@ -138,6 +144,7 @@ def _enable_errortracking():
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", dict()).get("plugin", None)
callback = event.get("extra", dict()).get("callback", None)
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
@@ -147,8 +154,8 @@ def _enable_errortracking():
matcher = lambda *args: True
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin):
# exception ignored for logger
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback):
# exception ignored for logger, plugin and/or callback
return None
elif isinstance(ignore, type):
@@ -25,7 +25,7 @@
</div>
</div>
<div class="control-group">
<label class="control-label" title="{{ _('Random unique instance ID') }}">{{ _('Instance ID') }}</label>
<label class="control-label" title="{{ _('Random unique instance ID')|edq }}">{{ _('Instance ID') }}</label>
<div class="controls">
<span style="padding-top: 5px; margin-bottom: 5px; display: inline-block" data-bind="text: settings.plugins.errortracking.unique_id() || 'N/A'"></span>
</div>
@@ -121,7 +121,7 @@ $(function() {
.done(self.requestData);
};
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: filename}),
showConfirmationDialog(_.sprintf(gettext("You are about to delete log file \"%(name)s\"."), {name: _.escape(filename)}),
perform);
};
@@ -172,11 +172,11 @@ $(function() {
var handler = function(filename) {
return OctoPrint.plugins.logging.deleteLog(filename)
.done(function() {
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: filename}), true);
deferred.notify(_.sprintf(gettext("Deleted %(filename)s..."), {filename: _.escape(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});
var short = _.sprintf(gettext("Deletion of %(filename)s failed, continuing..."), {filename: _.escape(filename)});
var long = _.sprintf(gettext("Deletion of %(filename)s failed: %(error)s"), {filename: _.escape(filename), error: _.escape(jqXHR.responseText)});
deferred.notify(short, long, false);
});
};
@@ -84,7 +84,7 @@
</select>
</div>
<div class="span1">
<a title="{{ _('Remove') }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
<a title="{{ _('Remove')|edq }}" class="btn btn-danger" data-bind="click: $parent.removeLogger"><i class="icon-trash"></i></a>
</div>
</div>
</div>
@@ -103,7 +103,7 @@
</select>
</div>
<div class="span1">
<a title="{{ _('Add') }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
<a title="{{ _('Add')|edq }}" class="btn btn-primary" data-bind="click: $root.addLogger"><i class="icon-plus"></i></a>
</div>
</div>
</div>
+25 -15
View File
@@ -19,14 +19,23 @@ _PROC_DT_MODEL_PATH = "/proc/device-tree/model"
_OCTOPI_VERSION_PATH = "/etc/octopi_version"
_VCGENCMD_THROTTLE = "/usr/bin/vcgencmd get_throttled"
### uncomment for local debugging
#import sys
#base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
#_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
#_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
#_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
#import itertools
#_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70000"))
_CHECK_INTERVAL_OK = 300
_CHECK_INTERVAL_THROTTLED = 30
__LOCAL_DEBUG = False
if __LOCAL_DEBUG:
### mocks & settings for local debugging
import sys
base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
import itertools
_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005"))
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
@@ -135,8 +144,11 @@ def get_proc_dt_model():
def get_vcgencmd_throttled_state(command):
output = sarge.get_stdout(command)
#output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # for local debugging
if __LOCAL_DEBUG:
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
else:
output = sarge.get_stdout(command)
if not "throttled=0x" in output:
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
@@ -237,11 +249,9 @@ class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
# check state every 30s if something's currently amiss
return 30
return _CHECK_INTERVAL_THROTTLED
else:
# check state every 5min if nothing's currently amiss
return 300
return _CHECK_INTERVAL_OK
def _check_throttled_state_condition(self):
return self._throttle_functional
@@ -305,7 +315,7 @@ __plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your Pi in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi,"
"provide additional information about your Pi, "
"which will make it more tricky to help you if you need support.")
__plugin_license__ = "AGPLv3"
@@ -1,4 +1,4 @@
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?') }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage') }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat') }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
<a href="https://faq.octoprint.org/pi-issues" target="_blank" rel="noopener noreferrer" data-bind="visible: currentIssue() || pastIssue(), popover: { placement: 'bottom', title: '{{ _('What do the symbols mean?')|esq }}', html: true, content: popoverContent, trigger: 'hover' }" style="display: none">
<span data-bind="visible: currentUndervoltage() || pastUndervoltage(), css: {'pi_support_state_pulsate': currentUndervoltage}" title="{{ _('Undervoltage')|edq }}"><i class="fa fa-bolt"></i><i class="fa fa-exclamation"></i></span>
<span data-bind="visible: currentOverheat() || pastOverheat(), css: {'pi_support_state_pulsate': currentOverheat}" title="{{ _('Overheat')|edq }}"><i class="fa fa-thermometer-full"></i><i class="fa fa-exclamation"></i></span>
</a>
+229 -15
View File
@@ -36,10 +36,18 @@ import threading
from datetime import datetime
_DATA_FORMAT_VERSION = "v2"
try:
from os import scandir
except:
from scandir import scandir
_DATA_FORMAT_VERSION = "v3"
def map_repository_entry(entry):
if not isinstance(entry, dict):
return None
result = copy.deepcopy(entry)
if not "follow_dependency_links" in result:
@@ -113,20 +121,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_plugins = []
self._repository_cache_path = None
self._repository_cache_ttl = 0
self._repository_mtime = None
self._notices = dict()
self._notices_available = False
self._notices_cache_path = None
self._notices_cache_ttl = 0
self._notices_mtime = None
self._orphans = None
self._console_logger = None
self._get_throttled = lambda: False
def initialize(self):
self._console_logger = logging.getLogger("octoprint.plugins.pluginmanager.console")
self._repository_cache_path = os.path.join(self.get_plugin_data_folder(), "plugins.json")
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_path = os.path.join(self.get_plugin_data_folder(), "notices.json")
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
self._pip_caller = LocalPipCaller(force_user=self._settings.get_boolean(["pip_force_user"]))
self._pip_caller.on_log_call = self._log_call
@@ -169,6 +184,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if helpers and "get_throttled" in helpers:
self._get_throttled = helpers["get_throttled"]
if self._settings.get_boolean(["ignore_throttled"]):
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Plugin Manager plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
# decouple repository fetching from server startup
self._fetch_all_data(do_async=True)
@@ -182,8 +203,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
notices_ttl=6*60,
pip_args=None,
pip_force_user=False,
confirm_disable=False,
dependency_links=False,
hidden=[]
hidden=[],
ignore_throttled=False
)
def on_settings_save(self, data):
@@ -192,6 +215,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._repository_cache_ttl = self._settings.get_int(["repository_ttl"]) * 60
self._notices_cache_ttl = self._settings.get_int(["notices_ttl"]) * 60
self._pip_caller.force_user = self._settings.get_boolean(["pip_force_user"])
self._confirm_disable = self._settings.global_get_boolean(["confirm_disable"])
##~~ AssetPlugin
@@ -278,6 +302,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
"uninstall": ["plugin"],
"enable": ["plugin"],
"disable": ["plugin"],
"cleanup": ["plugin"],
"cleanup_all": [],
"refresh_repository": []
}
@@ -288,19 +314,22 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
from octoprint.server import safe_mode
refresh_repository = request.values.get("refresh_repository", "false") in valid_boolean_trues
if refresh_repository:
if refresh_repository or not self._is_repository_cache_valid():
self._repository_available = self._refresh_repository()
refresh_notices = request.values.get("refresh_notices", "false") in valid_boolean_trues
if refresh_notices:
if refresh_notices or not self._is_notices_cache_valid():
self._notices_available = self._refresh_notices()
refresh_orphan = request.values.get("refresh_orphans", "false") in valid_boolean_trues
def view():
return jsonify(plugins=self._get_plugins(),
repository=dict(
available=self._repository_available,
plugins=self._repository_plugins
),
orphan_data=self._get_orphans(refresh=refresh_orphan),
os=get_os(),
octoprint=get_octoprint_version_string(),
pip=dict(
@@ -327,6 +356,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
hash_update(repr(self._repository_plugins))
hash_update(str(self._notices_available))
hash_update(repr(self._notices))
hash_update(repr(self._get_orphans()))
hash_update(repr(safe_mode))
hash_update(repr(self._connectivity_checker.online))
hash_update(repr(_DATA_FORMAT_VERSION))
@@ -337,7 +367,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return with_revalidation_checking(etag_factory=lambda *args, **kwargs: etag(),
condition=lambda *args, **kwargs: condition(),
unless=lambda: refresh_repository or refresh_notices)(view)()
unless=lambda: refresh_repository or refresh_notices or refresh_orphan)(view)()
def on_api_command(self, command, data):
if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can():
@@ -364,7 +394,20 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return make_response("Unknown plugin: %s" % plugin_name, 404)
plugin = self._plugin_manager.plugins[plugin_name]
return self.command_uninstall(plugin)
return self.command_uninstall(plugin, cleanup=data.get("cleanup", False))
elif command == "cleanup":
plugin = data["plugin"]
try:
plugin = self._plugin_manager.plugins[plugin]
except KeyError:
# not installed, we are cleaning up left overs, that's ok
pass
return self.command_cleanup(plugin, include_disabled=True)
elif command == "cleanup_all":
return self.command_cleanup_all()
elif command == "enable" or command == "disable":
plugin_name = data["plugin"]
@@ -375,6 +418,12 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return self.command_toggle(plugin, command)
def command_install(self, url=None, path=None, force=False, reinstall=None, dependency_links=False):
throttled = self._get_throttled()
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
# currently throttled, we refuse to run
return make_response("System is currently throttled, refusing to install "
"anything due to possible stability issues", 409)
if url is not None:
if not any(map(lambda scheme: url.startswith(scheme + "://"), self.URL_SCHEMES)):
raise ValueError("Invalid URL to pip install from")
@@ -539,7 +588,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._send_result_notification("install", result)
return jsonify(result)
def command_uninstall(self, plugin):
def command_uninstall(self, plugin, cleanup=False):
if plugin.key == "pluginmanager":
return make_response("Can't uninstall Plugin Manager", 403)
@@ -588,7 +637,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._logger.warning("Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format(**locals()))
return make_response("Could not uninstall plugin, its origin is unknown")
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin)
needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup
needs_refresh = plugin.implementation and isinstance(plugin.implementation, octoprint.plugin.ReloadNeedingPlugin)
needs_reconnect = self._plugin_manager.has_any_of_hooks(plugin, self._reconnect_hooks) and self._printer.is_operational()
@@ -628,8 +677,108 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
needs_reconnect=needs_reconnect,
plugin=self._to_external_plugin(plugin))
self._send_result_notification("uninstall", result)
self._logger.info("Plugin {} uninstalled".format(plugin.key))
self._cleanup_disabled(plugin.key)
if cleanup:
self.command_cleanup(plugin.key, result_notifications=False)
return jsonify(result)
def command_cleanup(self, plugin, include_disabled=False, result_notifications=True, settings_save=True):
if isinstance(plugin, basestring):
key = result_value = plugin
else:
key = plugin.key
result_value = self._to_external_plugin(plugin)
message = "Cleaning up plugin {}...".format(key)
self._logger.info(message)
self._log_stdout(message)
# delete plugin settings
self._cleanup_settings(key)
# delete plugin disabled entry
if include_disabled:
self._cleanup_disabled(key)
# delete plugin data folder
result_data = True
if not self._cleanup_data(key):
message = "Could not delete data folder of plugin {}".format(key)
self._logger.exception(message)
self._log_stderr(message)
result_data = False
if settings_save:
self._settings.save()
result = dict(result=result_data,
needs_restart=True,
plugin=result_value)
if result_notifications:
self._send_result_notification("cleanup", result)
# cleaning orphan cache
self._orphans = None
return jsonify(result)
def command_cleanup_all(self):
orphans = self._get_orphans()
cleaned_up = set()
for orphan in sorted(orphans.keys()):
self.command_cleanup(orphan,
include_disabled=True,
result_notifications=False,
settings_save=False)
cleaned_up.add(orphan)
self._settings.save()
result = dict(result=True,
needs_restart=len(cleaned_up) > 0,
cleaned_up=sorted(list(cleaned_up)))
self._send_result_notification("cleanup_all", result)
self._logger.info("Cleaned up all data, {} left overs removed".format(len(cleaned_up)))
# cleaning orphan cache
self._orphans = None
return jsonify(result)
def _cleanup_disabled(self, plugin):
# delete from disabled list
disabled = self._settings.global_get(["plugins", "_disabled"])
try:
disabled.remove(plugin)
except ValueError:
# not in list, ok
pass
self._settings.global_set(["plugins", "_disabled"], disabled)
def _cleanup_settings(self, plugin):
# delete plugin settings
self._settings.global_set(["plugins", plugin], None)
return True
def _cleanup_data(self, plugin):
import os
import shutil
data_folder = os.path.join(self._settings.getBaseFolder("data"), plugin)
if os.path.exists(data_folder):
try:
shutil.rmtree(data_folder)
return True
except Exception:
self._logger.exception("Could not delete plugin data folder at {}".format(data_folder))
return False
else:
return True
def command_toggle(self, plugin, command):
if plugin.key == "pluginmanager":
return make_response("Can't enable/disable Plugin Manager", 400)
@@ -717,7 +866,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
inapplicable_arguments = self.__class__.PIP_INAPPLICABLE_ARGUMENTS.get(args[0], list())
for inapplicable_argument in inapplicable_arguments:
additional_args = re.sub("(^|\s)" + re.escape(inapplicable_argument) + "\\b", "", additional_args)
additional_args = re.sub(r"(^|\s)" + re.escape(inapplicable_argument) + r"\\b", "", additional_args)
if additional_args:
args.append(additional_args)
@@ -801,16 +950,25 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
run()
def _is_repository_cache_valid(self, mtime=None):
import time
if mtime is None:
mtime = self._repository_mtime
if mtime is None:
return False
return mtime + self._repository_cache_ttl >= time.time() > mtime
def _fetch_repository_from_disk(self):
repo_data = None
if os.path.isfile(self._repository_cache_path):
import time
mtime = os.path.getmtime(self._repository_cache_path)
if mtime + self._repository_cache_ttl >= time.time() > mtime:
if self._is_repository_cache_valid(mtime=mtime):
try:
import json
with io.open(self._repository_cache_path, 'rt', encoding='utf-8') as f:
repo_data = json.load(f)
self._repository_mtime = mtime
self._logger.info("Loaded plugin repository data from disk, was still valid")
except Exception:
self._logger.exception("Error while loading repository data from {}".format(self._repository_cache_path))
@@ -828,17 +986,27 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
r.raise_for_status()
self._logger.info("Loaded plugin repository data from {}".format(repository_url))
except Exception as e:
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=str(e)))
self._logger.exception("Could not fetch plugins from repository at {repository_url}: {message}".format(repository_url=repository_url, message=e))
return None
repo_data = r.json()
try:
repo_data = r.json()
except Exception as e:
self._logger.exception("Error while reading repository data: {}".format(e))
return None
# validation
if not isinstance(repo_data, (list, tuple)):
self._logger.warn("Invalid repository data: expected a list, got {!r}".format(repo_data))
return None
try:
import json
with octoprint.util.atomic_write(self._repository_cache_path, mode='wb') as f:
f.write(to_bytes(json.dumps(repo_data)))
self._repository_mtime = os.path.getmtime(self._repository_cache_path)
except Exception as e:
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, str(e)))
self._logger.exception("Error while saving repository data to {}: {}".format(self._repository_cache_path, e))
return repo_data
@@ -848,19 +1016,29 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if repo_data is None:
return False
self._repository_plugins = list(map(map_repository_entry, repo_data))
self._repository_plugins = list(filter(lambda x: x is not None,
map(map_repository_entry, repo_data)))
return True
def _is_notices_cache_valid(self, mtime=None):
import time
if mtime is None:
mtime = self._notices_mtime
if mtime is None:
return False
return mtime + self._notices_cache_ttl >= time.time() > mtime
def _fetch_notices_from_disk(self):
notice_data = None
if os.path.isfile(self._notices_cache_path):
import time
mtime = os.path.getmtime(self._notices_cache_path)
if mtime + self._notices_cache_ttl >= time.time() > mtime:
if self._is_notices_cache_valid(mtime=mtime):
try:
import json
with io.open(self._notices_cache_path, 'rt', encoding='utf-8') as f:
notice_data = json.load(f)
self._notices_mtime = mtime
self._logger.info("Loaded notice data from disk, was still valid")
except Exception:
self._logger.exception("Error while loading notices from {}".format(self._notices_cache_path))
@@ -887,6 +1065,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
import json
with octoprint.util.atomic_write(self._notices_cache_path, mode="wb") as f:
f.write(to_bytes(json.dumps(notice_data)))
self._notices_mtime = os.path.getmtime(self._notices_cache_path)
except Exception as e:
self._logger.exception("Error while saving notices to {}: {}".format(self._notices_cache_path, str(e)))
return notice_data
@@ -924,6 +1103,41 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
self._notices = notices
return True
def _get_orphans(self, refresh=False):
from collections import defaultdict
if self._orphans is not None and not refresh:
return self._orphans
installed_keys = self._plugin_manager.plugins.keys()
orphans = defaultdict(lambda: dict(settings=False, data=False, disabled=False))
# settings
for key in list(self._settings.global_get(["plugins"]).keys()):
if key.startswith("_"):
# internal key, like _disabled
continue
if key not in installed_keys:
orphans[key]["settings"] = True
# data
for entry in scandir(self._settings.getBaseFolder("data")):
if not entry.is_dir():
continue
if entry.name not in installed_keys:
orphans[entry.name]["data"] = True
# disabled
disabled = self._settings.global_get(["plugins", "_disabled"])
for key in disabled:
if key not in installed_keys:
orphans[key]["disabled"] = True
self._orphans = dict(**orphans)
return self._orphans
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
@@ -10,18 +10,21 @@
};
OctoPrintPluginManagerClient.prototype.get = function(refresh, opts) {
var refresh_repo, refresh_notices;
var refresh_repo, refresh_notices, refresh_orphans;
if (_.isPlainObject(refresh)) {
refresh_repo = refresh.repo || false;
refresh_notices = refresh.notices || false;
refresh_orphans = refresh.orphans || false;
} else {
refresh_repo = refresh;
refresh_notices = false;
refresh_orphans = false;
}
var query = [];
if (refresh_repo) query.push("refresh_repository=true");
if (refresh_notices) query.push("refresh_notices=true");
if (refresh_orphans) query.push("refresh_orphans=true");
return this.base.get(this.base.getSimpleApiUrl("pluginmanager") + ((query.length) ? "?" + query.join("&") : ""), opts);
};
@@ -52,11 +55,30 @@
return this.base.simpleApiCommand("pluginmanager", "install", data, opts);
};
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, opts) {
OctoPrintPluginManagerClient.prototype.uninstall = function(plugin, cleanup, opts) {
// backwards compatibility to former argument list (plugin, opts)
if (arguments.length === 2 && typeof cleanup === "object") {
opts = cleanup;
cleanup = false;
}
var data = {
plugin: plugin,
cleanup: !!cleanup
};
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
};
OctoPrintPluginManagerClient.prototype.cleanup = function(plugin, opts) {
var data = {
plugin: plugin
};
return this.base.simpleApiCommand("pluginmanager", "uninstall", data, opts);
return this.base.simpleApiCommand("pluginmanager", "cleanup", data, opts);
};
OctoPrintPluginManagerClient.prototype.cleanupAll = function(plugin, opts) {
var data = {};
return this.base.simpleApiCommand("pluginmanager", "cleanup_all", data, opts);
};
OctoPrintPluginManagerClient.prototype.enable = function(plugin, opts) {
@@ -1 +1 @@
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
#settings_plugin_pluginmanager_pluginlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_name,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_name{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_pluginlist table td.settings_plugin_plugin_manager_plugins_actions a.disabled,#settings_plugin_pluginmanager_pluginlist table th.settings_plugin_plugin_manager_plugins_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_orphanlist{display:block;width:auto;max-height:400px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_id,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_id{text-overflow:ellipsis;text-align:left}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions{text-align:center;width:80px}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a{text-decoration:none;color:#000}#settings_plugin_pluginmanager_orphanlist table td.settings_plugin_plugin_manager_orphans_actions a.disabled,#settings_plugin_pluginmanager_orphanlist table th.settings_plugin_plugin_manager_orphans_actions a.disabled{color:#ccc;cursor:default}#settings_plugin_pluginmanager_repositorydialog h4{position:relative}#settings_plugin_pluginmanager_repositorydialog h4 a.dropdown-toggle{color:inherit;text-decoration:none;font-size:14px}#settings_plugin_pluginmanager_repositorydialog h4 ul.dropdown-menu{font-size:14px}#settings_plugin_pluginmanager_repositorydialog .form-search{text-align:center;margin-bottom:5px!important}#settings_plugin_pluginmanager_repositorydialog .form-inline{padding:5px 10px 5px 5px;margin-bottom:0}#settings_plugin_pluginmanager_repositorydialog .form-inline .help-block{margin-bottom:0;font-size:85%}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable{overflow:hidden;width:100%;height:300px;background-image:url(../img/repo_unavailable.png);text-align:center;display:table}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_empty div,#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_unavailable div{display:table-cell;vertical-align:middle}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list{width:auto;height:300px;overflow-x:hidden;overflow-y:scroll;padding-right:2px}#settings_plugin_pluginmanager_repositorydialog #settings_plugin_pluginmanager_repositorydialog_list .entry{border-bottom:1px solid #ddd;padding:5px}#settings_plugin_pluginmanager_workingdialog_output .message{font-weight:700}#settings_plugin_pluginmanager_workingdialog_output .error{font-weight:700;color:#900}#settings_plugin_pluginmanager_workingdialog_output .stdout{color:#333}#settings_plugin_pluginmanager_workingdialog_output .stderr{color:#900}#settings_plugin_pluginmanager_workingdialog_output .call{color:#009}
@@ -8,12 +8,17 @@ $(function() {
self.systemViewModel = parameters[3];
self.access = parameters[4];
// optional
self.piSupport = parameters[5];
self.config_repositoryUrl = ko.observable();
self.config_repositoryTtl = ko.observable();
self.config_noticesUrl = ko.observable();
self.config_noticesTtl = ko.observable();
self.config_pipAdditionalArgs = ko.observable();
self.config_pipForceUser = ko.observable();
self.config_confirmUninstall = ko.observable();
self.config_confirmDisable = ko.observable();
self.configurationDialog = $("#settings_plugin_pluginmanager_configurationdialog");
@@ -28,10 +33,22 @@ $(function() {
}
},
{
"bundled": function(item) {
return item.bundled;
},
"3rdparty": function(item) {
return !item.bundled;
},
"enabled": function(item) {
return item.enabled;
},
"disabled": function(item) {
return !item.enabled;
}
},
"name",
[],
[],
[["bundled", "3rdparty"], ["enabled", "disabled"]],
0
);
@@ -65,6 +82,23 @@ $(function() {
0
);
self.orphans = new ItemListHelper(
"plugin.pluginmanager.orphans",
{
"identifier": function (a, b) {
// sorts ascending
if (a["identifier"].toLocaleLowerCase() < b["identifier"].toLocaleLowerCase()) return -1;
if (a["identifier"].toLocaleLowerCase() > b["identifier"].toLocaleLowerCase()) return 1;
return 0;
}
},
{},
"identifier",
[],
[],
0
);
self.uploadElement = $("#settings_plugin_pluginmanager_repositorydialog_upload");
self.uploadButton = $("#settings_plugin_pluginmanager_repositorydialog_upload_start");
@@ -75,6 +109,11 @@ $(function() {
self.performRepositorySearch();
});
self.listingSearchQuery = ko.observable();
self.listingSearchQuery.subscribe(function() {
self.performListingSearch();
});
self.installUrl = ko.observable();
self.uploadFilename = ko.observable();
@@ -145,7 +184,7 @@ $(function() {
});
self.enableManagement = ko.pureComputed(function() {
return !self.printerState.isPrinting();
return !self.printerState.isBusy();
});
self.enableToggle = function(data) {
@@ -164,10 +203,20 @@ $(function() {
&& !data.pending_uninstall;
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && self.online() && self.isCompatible(data);
self.enableCleanup = function(data) {
return self.enableManagement()
&& data.key !== 'pluginmanager'
&& !data.pending_uninstall;
};
self.enableRepoInstall = function(data) {
return self.enableManagement() && self.pipAvailable() && !self.safeMode() && !self.throttled() && self.online() && self.isCompatible(data);
};
self.throttled = ko.pureComputed(function() {
return self.piSupport && self.piSupport.currentIssue() && !self.settingsViewModel.settings.plugins.pluginmanager.ignore_throttled();
});
self.invalidUrl = ko.pureComputed(function() {
// supported pip install URL schemes, according to https://pip.pypa.io/en/stable/reference/pip_install/
var allowedUrlSchemes = ["http", "https",
@@ -192,6 +241,7 @@ $(function() {
return self.enableManagement()
&& self.pipAvailable()
&& !self.safeMode()
&& !self.throttled()
&& self.online()
&& url !== undefined
&& url.trim() !== ""
@@ -217,6 +267,7 @@ $(function() {
return self.enableManagement()
&& self.pipAvailable()
&& !self.safeMode()
&& !self.throttled()
&& name !== undefined
&& name.trim() !== ""
&& !self.invalidArchive();
@@ -267,9 +318,21 @@ $(function() {
}
});
self.performListingSearch = function() {
var query = self.listingSearchQuery();
if (query !== undefined && query.trim() !== "") {
query = query.toLocaleLowerCase();
self.plugins.changeSearchFunction(function (entry) {
return entry && (entry["name"].toLocaleLowerCase().indexOf(query) > -1 || (entry.description && entry.description.toLocaleLowerCase().indexOf(query) > -1));
});
} else {
self.plugins.resetSearch();
}
};
self.performRepositorySearch = function() {
var query = self.repositorySearchQuery();
if (query !== undefined && query.trim() != "") {
if (query !== undefined && query.trim() !== "") {
query = query.toLocaleLowerCase();
self.repositoryplugins.changeSearchFunction(function(entry) {
return entry && (entry["title"].toLocaleLowerCase().indexOf(query) > -1 || entry["description"].toLocaleLowerCase().indexOf(query) > -1);
@@ -282,6 +345,7 @@ $(function() {
self.fromResponse = function(data, options) {
self._fromPluginsResponse(data.plugins, options);
self._fromOrphanResponse(data.orphan_data, options);
self._fromRepositoryResponse(data.repository, options);
self._fromPipResponse(data.pip, options);
@@ -315,6 +379,14 @@ $(function() {
self.plugins.updateItems(data);
};
self._fromOrphanResponse = function(data) {
var orphans = [];
_.each(data, function(value, key) {
orphans.push({identifier: key, settings: value.settings, data: value.data});
});
self.orphans.updateItems(orphans);
};
self._fromRepositoryResponse = function(data) {
self.repositoryAvailable(data.available);
if (data.available) {
@@ -350,17 +422,18 @@ $(function() {
if (!_.isPlainObject(options)) {
options = {
refresh_repo: options,
refresh_orphans: false,
refresh_notices: false,
eval_notices: false
};
}
options.refresh_repo = options.refresh_repo || false;
options.refresh_orphans = options.refresh_orphans || false;
options.refresh_notices = options.refresh_notices || false;
options.eval_notices = options.eval_notices || false;
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices})
OctoPrint.plugins.pluginmanager.get({repo: options.refresh_repo, notices: options.refresh_notices, orphans: options.refresh_orphans})
.done(function(data) {
self.fromResponse(data, options);
});
@@ -395,14 +468,15 @@ $(function() {
.done(onSuccess)
.fail(onError);
} else {
var perform = function() {
var performDisabling = function() {
OctoPrint.plugins.pluginmanager.disable(data.key)
.done(onSuccess)
.fail(onError);
};
// always warn if plugin is marked "disabling discouraged"
if (data.disabling_discouraged) {
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: data.name})
var message = _.sprintf(gettext("You are about to disable \"%(name)s\"."), {name: _.escape(data.name)})
+ "</p><p>" + data.disabling_discouraged;
showConfirmationDialog({
title: gettext("This is not recommended"),
@@ -410,10 +484,21 @@ $(function() {
question: gettext("Do you still want to disable it?"),
cancel: gettext("Keep enabled"),
proceed: gettext("Disable anyway"),
onproceed: perform
})
onproceed: performDisabling
});
}
// warn if global "warn disabling" setting is set"
else if (self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable()) {
showConfirmationDialog({
message: _.sprintf(gettext("You are about to disable \"%(name)s\""), {name: _.escape(data.name)}),
cancel: gettext("Keep enabled"),
proceed: gettext("Disable plugin"),
onproceed: performDisabling,
nofade: true
});
} else {
perform();
// otherwise just go ahead and disable...
performDisabling();
}
}
};
@@ -447,6 +532,10 @@ $(function() {
return;
}
if (self.throttled()) {
return;
}
if (url === undefined) {
url = self.installUrl();
}
@@ -460,13 +549,13 @@ $(function() {
if (!reinstall) {
workTitle = gettext("Installing plugin...");
if (name) {
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
workText = _.sprintf(gettext("Installing plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
} else {
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: url});
workText = _.sprintf(gettext("Installing plugin from %(url)s..."), {url: _.escape(url)});
}
} else {
workTitle = gettext("Reinstalling plugin...");
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: url, name: name});
workText = _.sprintf(gettext("Reinstalling plugin \"%(name)s\" from %(url)s..."), {url: _.escape(url), name: _.escape(name)});
}
self._markWorking(workTitle, workText);
@@ -510,25 +599,119 @@ $(function() {
}
if (data.bundled) return;
if (data.key == "pluginmanager") return;
if (data.key === "pluginmanager") return;
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: data.name}));
// defining actual uninstall logic as functor in order to handle
// the confirm/no-confirm logic without duplication of logic
var performUninstall = function(cleanup) {
self._markWorking(gettext("Uninstalling plugin..."), _.sprintf(gettext("Uninstalling plugin \"%(name)s\""), {name: _.escape(data.name)}));
OctoPrint.plugins.pluginmanager.uninstall(data.key)
.done(function() {
self.requestData();
})
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
OctoPrint.plugins.pluginmanager.uninstall(data.key, cleanup)
.done(function() {
self.requestData();
})
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
})
.always(function() {
self._markDone();
});
})
.always(function() {
self._markDone();
});
};
showConfirmationDialog({
message: _.sprintf(gettext("You are about to uninstall the plugin \"%(name)s\""), {name: _.escape(data.name)}),
cancel: gettext("Keep installed"),
proceed: [
gettext("Uninstall"),
gettext("Uninstall & clean up data")
],
onproceed: function(button) {
// buttons: 0=uninstall, 1=uninstall&cleanup
performUninstall(button === 1)
},
nofade: true
});
};
self.cleanupPlugin = function(data) {
var key, name;
if (_.isObject(data)) {
key = data.key;
name = data.name;
} else {
key = name = data;
}
if (!self.loginState.isAdmin()) {
return;
}
if (key === "pluginmanager") return;
var performCleanup = function() {
self._markWorking(gettext("Cleaning up plugin data..."), _.sprintf(gettext("Cleaning up data of plugin \"%(name)s\""), {name: _.escape(name)}));
OctoPrint.plugins.pluginmanager.cleanup(key)
.done(function() {
self.requestData();
})
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
})
.always(function() {
self._markDone();
})
};
showConfirmationDialog({
message: _.sprintf(gettext("You are about to cleanup the plugin data of \"%(name)s\". This operation cannot be reversed."), {name: _.escape(name)}),
cancel: gettext("Keep data"),
proceed: gettext("Cleanup data"),
onproceed: performCleanup,
nofade: true
});
};
self.cleanupAll = function() {
if (!self.loginState.isAdmin()) {
return;
}
var performCleanup = function() {
var title = gettext("Cleaning up all left over plugin data...");
self._markWorking(title, title);
OctoPrint.plugins.pluginmanager.cleanupAll()
.fail(function() {
new PNotify({
title: gettext("Something went wrong"),
text: gettext("Please consult octoprint.log for details"),
type: "error",
hide: false
});
})
.always(function() {
self._markDone();
})
};
showConfirmationDialog({
message: gettext("You are about to cleanup left over plugin settings and data of plugins no longer installed. This operation cannot be reversed."),
cancel: gettext("Keep data"),
proceed: gettext("Cleanup all data"),
onproceed: performCleanup,
nofade: true
});
};
self.refreshRepository = function() {
@@ -597,7 +780,8 @@ $(function() {
notices: notices,
notices_ttl: noticesTtl,
pip_args: pipArgs,
pip_force_user: self.config_pipForceUser()
pip_force_user: self.config_pipForceUser(),
confirm_disable: self.config_confirmDisable(),
}
}
};
@@ -615,6 +799,7 @@ $(function() {
self.config_noticesTtl(self.settingsViewModel.settings.plugins.pluginmanager.notices_ttl());
self.config_pipAdditionalArgs(self.settingsViewModel.settings.plugins.pluginmanager.pip_args());
self.config_pipForceUser(self.settingsViewModel.settings.plugins.pluginmanager.pip_force_user());
self.config_confirmDisable(self.settingsViewModel.settings.plugins.pluginmanager.confirm_disable());
};
self.installed = function(data) {
@@ -671,13 +856,21 @@ $(function() {
line = gettext("Disable <em>%(plugin)s</em>: %(result)s");
break;
}
case "cleanup": {
line = gettext("Cleanup <em>%(plugin)s</em>: %(result)s");
break;
}
case "cleanup_all": {
line = gettext("Cleanup all: %(result)s");
break;
}
default: {
return;
}
}
text += "<li>"
+ _.sprintf(line, {plugin: step.plugin, result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
+ _.sprintf(line, {plugin: _.escape(step.plugin), result: step.result ? "<i class=\"fa fa-check\"></i>" : "<i class=\"fa fa-remove\"></i>"})
+ "</li>";
});
text += "</ul></p>";
@@ -855,16 +1048,16 @@ $(function() {
var title;
if (important) {
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: name});
title = _.sprintf(gettext("Important notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
} else {
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: name});
title = _.sprintf(gettext("Notice regarding plugin \"%(name)s\""), {name: _.escape(name)});
}
var text = "";
if (notification.versions && notification.versions.length > 0) {
var versions = _.map(notification.versions, function(v) { return (v == version) ? "<strong>" + v + "</strong>" : v; }).join(", ");
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: versions}) + "</small>";
text += "<small>" + _.sprintf(gettext("Affected versions: %(versions)s"), {versions: _.escape(versions)}) + "</small>";
} else {
text += "<small>" + gettext("Affected versions: all") + "</small>";
}
@@ -1060,7 +1253,11 @@ $(function() {
var name = "Unknown";
if (data.hasOwnProperty("plugin")) {
if (data.plugin !== "unknown") {
name = data.plugin.name;
if (_.isPlainObject(data.plugin)) {
name = data.plugin.name;
} else {
name = data.plugin;
}
}
}
@@ -1080,7 +1277,8 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: PluginManagerViewModel,
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel"],
dependencies: ["loginStateViewModel", "settingsViewModel", "printerStateViewModel", "systemViewModel", "accessViewModel", "piSupportViewModel"],
optional: ["piSupportViewModel"],
elements: ["#settings_plugin_pluginmanager"]
});
});
@@ -1,7 +1,10 @@
#settings_plugin_pluginmanager {
}
#settings_plugin_pluginmanager_pluginlist {
display: block;
width: auto;
height: 500px;
max-height: 400px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
@@ -33,6 +36,41 @@
}
}
#settings_plugin_pluginmanager_orphanlist {
display: block;
width: auto;
max-height: 400px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
margin-bottom: 1em;
table {
th, td {
&.settings_plugin_plugin_manager_orphans_id {
text-overflow: ellipsis;
text-align: left;
}
&.settings_plugin_plugin_manager_orphans_actions {
text-align: center;
width: 80px;
a {
text-decoration: none;
color: #000;
&.disabled {
color: #ccc;
cursor: default;
}
}
}
}
}
}
#settings_plugin_pluginmanager_repositorydialog {
h4 {
position: relative;
@@ -1,6 +1,6 @@
{% macro pluginmanager_printing() %}
<div class="alert" data-bind="visible: !enableManagement()">
{{ _('Take note that all plugin management functionality is disabled while your printer is printing.') }}
{{ _('Take note that all plugin management functionality is disabled while your printer is printing or paused.') }}
</div>
{% endmacro %}
@@ -20,6 +20,13 @@
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_throttled() %}
<div class="alert" data-bind="visible: throttled">{% trans %}
The system OctoPrint is running on is currently throttled. Due to that it's not possible to install new
plugins in order to avoid possible issues caused by system instability.
{% endtrans %}</div>
{% endmacro %}
{% macro pluginmanager_offline() %}
<div class="alert" data-bind="visible: !online()">{% trans %}
It looks like OctoPrint has currently no connection to the internet. Due to that it's not possible
@@ -27,77 +34,144 @@
{% endtrans %}</div>
{% endmacro %}
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
<ul class="nav nav-pills">
<li class="active">
<a href="#settings_plugin_pluginmanager_plugins" data-toggle="tab">{{ _('Plugins') }}</a>
</li>
<li>
<a href="#settings_plugin_pluginmanager_cleanup" data-toggle="tab">{{ _('Cleanup') }}</a>
</li>
</ul>
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration') }}"><i class="fa fa-wrench"></i></button>
</div>
<div class="tab-content">
<div class="tab-pane active" id="settings_plugin_pluginmanager_plugins">
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
{{ pluginmanager_throttled() }}
<h3>{{ _('Installed Plugins') }}</h3>
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.showPluginSettings(); }" title="{{ _('Plugin Configuration')|edq }}"><i class="fa fa-wrench"></i></button>
</div>
<div id="settings_plugin_pluginmanager_pluginlist">
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint') }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint') }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect') }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install') }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall') }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode') }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin') }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted') }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
<h3>{{ _('Installed Plugins') }}</h3>
<div style="margin-bottom: 1em" class="clearfix">
<input type="text" class="input-block search-query pull-left" data-bind="value: listingSearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
<div class="pull-right">
<div class="btn-group">
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('bundled'); plugins.removeFilter('3rdparty'); }, css: {active: !_.contains(plugins.currentFilters(), 'bundled') && !_.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show both bundled and third-party plugins')|edq }}">All</button>
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('bundled') }, css: {active: _.contains(plugins.currentFilters(), 'bundled')}" title="{{ _('Show only bundled plugins')|edq }}">{{ _('Bundled') }}</button>
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('3rdparty') }, css: {active: _.contains(plugins.currentFilters(), '3rdparty')}" title="{{ _('Show only third-party plugins')|edq }}">{{ _('3rd party') }}</button>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin') }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="btn-group">
<button class="btn btn-small" data-bind="click: function() { plugins.removeFilter('enabled'); plugins.removeFilter('disabled'); }, css: {active: !_.contains(plugins.currentFilters(), 'enabled') && !_.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show both enabled and disabled plugins')|edq }}">All</button>
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('enabled') }, css: {active: _.contains(plugins.currentFilters(), 'enabled')}" title="{{ _('Show only enabled plugins')|edq }}">{{ _('Enabled') }}</button>
<button class="btn btn-small" data-bind="click: function() { plugins.addFilter('disabled') }, css: {active: _.contains(plugins.currentFilters(), 'disabled')}" title="{{ _('Show only disabled plugins')|edq }}">{{ _('Disabled') }}</button>
</div>
</div>
</div>
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
<div id="settings_plugin_pluginmanager_pluginlist">
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_plugins_name">{{ _('Name') }}</th>
<th class="settings_plugin_plugin_manager_plugins_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: plugins.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_plugins_name">
<div data-bind="css: {muted: !enabled}"><span data-bind="text: name"></span> <span data-bind="visible: version">(<span data-bind="text: version"></span>)</span> <i title="{{ _('Bundled with OctoPrint')|edq }}" class="fa fa-th-large" data-bind="visible: bundled"></i> <i class="fa fa-lock" title="{{ _('Cannot be uninstalled through OctoPrint')|edq }}" data-bind="visible: !managable"></i> <i title="{{ _('Restart of OctoPrint needed for changes to take effect')|edq }}" class="fa fa-refresh" data-bind="visible: pending_enable || pending_disable || pending_install || pending_uninstall"></i> <i title="{{ _('Pending install')|edq }}" class="fa fa-plus" data-bind="visible: pending_install"></i> <i title="{{ _('Pending uninstall')|edq }}" class="fa fa-minus" data-bind="visible: pending_uninstall"></i> <i title="{{ _('Disabled due to safe mode')|edq }}" class="fa fa-medkit" data-bind="visible: safe_mode_victim"></i> <i class="fa fa-exclamation-triangle" title="{{ _('There are notices available regarding this plugin')|edq }}" data-bind="visible: notifications && notifications.length"></i> <i class="fa fa-ban" title="{{ _('This plugin is blacklisted')|edq }}" data-bind="visible: blacklisted"></i></div>
<div data-bind="visible: notifications && notifications.length"><a href="javascript:void(0)" class="text-error" style="text-decoration: underline" data-bind="click: function() { $root.showPluginNotifications($data) }, text: $root.showPluginNotificationsLinkText($data)"></a></div>
<div><small class="muted" data-bind="text: description">&nbsp;</small></div>
<div data-bind="css: {muted: !enabled}">
<small data-bind="visible: url"><i class="fa fa-home"></i> <a data-bind="attr: {href: url}" target="_blank" rel="noreferrer noopener">{{ _('Homepage') }}</a></small>
<small data-bind="visible: license"><i class="fa fa-gavel"></i> <span data-bind="text: license"></span></small>
<small data-bind="visible: author"><i class="fa fa-user"></i> <span data-bind="text: author"></span></small>
<small>&nbsp;</small>
</div>
</td>
<td class="settings_plugin_plugin_manager_plugins_actions">
<a href="#" data-bind="css: $root.toggleButtonCss($data), attr: {title: $root.toggleButtonTitle($data)}, enable: $root.enableToggle($data), click: function() { $root.togglePlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="css: {disabled: !$root.enableCleanup($data)}, enable: $root.enableCleanup($data), click: function() { $root.cleanupPlugin($data) }"></a>&nbsp;|&nbsp;<a href="#" class="fa fa-trash-o" title="{{ _('Uninstall Plugin')|edq }}" data-bind="css: {disabled: !$root.enableUninstall($data)}, enable: $root.enableUninstall($data), click: function() { $root.uninstallPlugin($data) }"></a>
</td>
</tr>
</tbody>
</table>
</div>
<div class="muted" data-bind="visible: pipAvailable()">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
</a>
</small>
</div>
<div class="hide">
<small>
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
</small>
</div>
</div>
<button class="btn btn-block" data-bind="click: $root.showRepository">{{ _('Get More...') }}</button>
<div class="muted">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
</a>
</small>
<div class="muted" data-bind="visible: pipAvailable()">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="fa toggle-arrow fa-caret-right"></i> Using pip of "<span data-bind="text: pipPython"></span>", Version <span data-bind="text: pipVersion"></span>
</a>
</small>
</div>
<div class="hide">
<small>
Installation directory: <span data-bind="text: pipInstallDir"></span> ("--user" flag: <span data-bind="text: pipUseUserString"></span>)<br />
Virtual environment: <span data-bind="text: pipVirtualEnvString"></span><br />
<span data-bind="visible: pipAdditionalArgs">Additional Arguments: <span data-bind="text: pipAdditionalArgs"></span></span>
</small>
</div>
</div>
<div class="muted">
<div>
<small>
<a href="javascript:void(0)" class="muted" onclick="$(this).children('i.toggle-arrow').toggleClass('fa-caret-right fa-caret-down').parent().parent().parent().next().slideToggle('fast')">
<i class="toggle-arrow fa fa-caret-right"></i> <span data-bind="text: noticeCountText"></span>
</a>
</small>
</div>
<div class="hide">
<small>
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> &middot;<!-- /ko -->
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
</small>
</div>
</div>
</div>
<div class="hide">
<small>
<!-- ko if: noticeCount() > 0 --><a href="javascript:void(0)" data-bind="click: function() { reshowNotices(); }">{{ _('Reshow current notices') }}</a> &middot;<!-- /ko -->
<a href="javascript:void(0)" data-bind="click: function() { refreshNotices(); }">{{ _('Refresh notices from repository') }}</a>
</small>
<div class="tab-pane" id="settings_plugin_pluginmanager_cleanup">
<div class="pull-right">
<button class="btn btn-small" data-bind="click: function() { $root.requestData({refresh_orphans: true}) }" title="{{ _('Refresh')|edq }}"><i class="fa fa-refresh"></i></button>
</div>
<h3>{{ _('Cleanup') }}</h3>
<div data-bind="visible: orphans.paginatedItems().length > 0">
<div id="settings_plugin_pluginmanager_orphanlist">
<table class="table table-striped table-hover table-condensed table-hover">
<thead>
<tr>
<th class="settings_plugin_plugin_manager_orphans_id">{{ _('Identifier') }}</th>
<th class="settings_plugin_plugin_manager_orphans_actions">{{ _('Actions') }}</th>
</tr>
</thead>
<tbody data-bind="foreach: orphans.paginatedItems">
<tr>
<td class="settings_plugin_plugin_manager_orphans_id">
<span data-bind="text: identifier"></span>
</td>
<td class="settings_plugin_plugin_manager_orphans_actions">
<a href="javascript:void(0)" class="fa fa-eraser" title="{{ _('Cleanup Plugin Data')|edq }}" data-bind="click: function() { $root.cleanupPlugin($data.identifier) }"></a>
</td>
</tr>
</tbody>
</table>
</div>
<button class="btn btn-danger btn-block" data-bind="click: $root.cleanupAll">{{ _('Cleanup all') }}</button>
</div>
<div data-bind="visible: orphans.paginatedItems().length == 0">
{{ _('Nothing to cleanup! There are no settings or data left over from plugins which are no longer installed.') }}
</div>
</div>
</div>
@@ -122,6 +196,7 @@
{{ pluginmanager_printing() }}
{{ pluginmanager_nopip() }}
{{ pluginmanager_safemode() }}
{{ pluginmanager_throttled() }}
{{ pluginmanager_offline() }}
<h4 style="position: relative">
{{ _('... from the <a href="%(url)s" target="_blank">Plugin Repository</a>', url='https://plugins.octoprint.org') }}
@@ -142,7 +217,7 @@
</h4>
<form class="form-search" data-bind="submit: performRepositorySearch">
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...') }}">
<input type="text" class="input-block search-query" data-bind="value: repositorySearchQuery, valueUpdate: 'input'" placeholder="{{ _('Search...')|edq }}">
</form>
<div data-bind="visible: repositoryAvailable() && repositoryplugins.paginatedItems().length > 0">
@@ -191,7 +266,7 @@
<form class="form-inline">
<div class="control-group row-fluid" data-bind="css: {error: invalidUrl}">
<div class="span9">
<input type="text" class="input-block-level" data-bind="value: installUrl, valueUpdate: 'input'" placeholder="{{ _('Enter URL...') }}" >
<input type="text" class="input-block-level" data-bind="value: installUrl, valueUpdate: 'input'" placeholder="{{ _('Enter URL...')|edq }}" >
</div>
<button class="btn btn-primary span3" data-bind="enable: enableUrlInstall, css: {disabled: !enableUrlInstall()}, click: function() { if (enableUrlInstall()) { $root.installPlugin(); } }">{{ _('Install') }}</button>
</div>
@@ -241,18 +316,30 @@
</div>
<div class="modal-body">
<form class="form-horizontal">
<fieldset>
<legend>{{ _('Confirmations') }}</legend>
<div class="control-group" title="{{ _('Confirm before disabling a plugin')|edq }}">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_confirmDisable"> {{ _('Confirm before disabling a plugin') }}
</label>
</div>
</div>
</fieldset>
<p>{% trans %}You should normally <strong>not</strong> have to change <strong>any</strong> of the following settings, they are purely provided for convenience here.{% endtrans %}</p>
<fieldset>
<legend>{{ _('Plugin repository configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.') }}">
<div class="control-group" title="{{ _('URL of the Plugin Repository to use. You should normally not have to change this.')|edq }}">
<label class="control-label">{{ _('Repository URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_repositoryUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.') }}">
<div class="control-group" title="{{ _('How long to cache repository data, in minutes. You should normally not have to change this.')|edq }}">
<label class="control-label">{{ _('Repository cache TTL') }}</label>
<div class="controls">
<div class="input-append">
@@ -266,13 +353,13 @@
<fieldset>
<legend>{{ _('Notices configuration') }}</legend>
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.') }}">
<div class="control-group" title="{{ _('URL of the Notices source to use. You should normally not have to change this.')|edq }}">
<label class="control-label">{{ _('Notices URL') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_noticesUrl">
</div>
</div>
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.') }}">
<div class="control-group" title="{{ _('How long to cache notices, in minutes. You should normally not have to change this.')|edq }}">
<label class="control-label">{{ _('Notices cache TTL') }}</label>
<div class="controls">
<div class="input-append">
@@ -286,7 +373,7 @@
<fieldset>
<legend>{{ _('pip configuration') }}</legend>
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.') }}">
<div class="control-group" title="{{ _('Additional arguments for the pip command. You should normally not have to change this.')|edq }}">
<label class="control-label">{{ _('Additional arguments') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipAdditionalArgs">
@@ -189,7 +189,7 @@ __plugin_author__ = "Gina Häußge"
__plugin_url__ = "http://docs.octoprint.org/en/master/bundledplugins/printer_safety_check.html"
__plugin_description__ = "Checks for unsafe printers/printer firmwares"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"check if the printer it is connected to has a known safety"
"check if the printer it is connected to has a known safety "
"issue and inform you about that fact.")
__plugin_license__ = "AGPLv3"
__plugin_implementation__ = PrinterSafetyCheckPlugin()
@@ -68,7 +68,7 @@ class AnycubicCheck(Check):
def _broken_version(self, line):
version_str = line[len(self.VERSION):]
version = get_comparable_version(version_str, base=True)
if version is not None and version <= self.FIXED_VERSION:
if version is not None and version < self.FIXED_VERSION:
return True
else:
return False
+113 -21
View File
@@ -35,9 +35,10 @@ from octoprint.util.pip import LocalPipCaller
import octoprint.settings
# OctoPi 0.15+
MINIMUM_PYTHON = "2.7.9"
MINIMUM_SETUPTOOLS = "5.5.1"
MINIMUM_PIP = "9.0.1"
MINIMUM_SETUPTOOLS = "39.0.1"
MINIMUM_PIP = "9.0.3"
##~~ Plugin
@@ -77,6 +78,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger = None
self._get_throttled = lambda: False
def initialize(self):
self._console_logger = logging.getLogger("octoprint.plugins.softwareupdate.console")
@@ -119,6 +122,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._console_logger.setLevel(logging.DEBUG)
self._console_logger.propagate = False
helpers = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if helpers and "get_throttled" in helpers:
self._get_throttled = helpers["get_throttled"]
if self._settings.get_boolean(["ignore_throttled"]):
self._logger.warn("!!! THROTTLE STATE IGNORED !!! You have configured the Software Update plugin to ignore an active throttle state of the underlying system. You might run into stability issues or outright corrupt your install. Consider fixing the throttling issue instead of suppressing it.")
def on_after_startup(self):
self._check_environment()
self.get_current_versions()
@@ -130,9 +139,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._configured_checks = self._settings.get(["checks"], merged=True)
update_check_hooks = self._plugin_manager.get_hooks("octoprint.plugin.softwareupdate.check_config")
check_providers = self._settings.get(["check_providers"], merged=True)
if not isinstance(check_providers, dict):
check_providers = dict()
check_providers = dict()
effective_configs = dict()
@@ -180,9 +187,6 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
for key, config in effective_configs.items():
self._configured_checks[key] = config
self._settings.set(["check_providers"], check_providers)
self._settings.save()
# we only want to process checks that came from plugins for
# which the plugins are still installed and enabled
config_checks = self._settings.get(["checks"])
@@ -291,11 +295,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
},
},
"pip_command": None,
"check_providers": {},
"cache_ttl": 24 * 60,
"notify_users": True
"notify_users": True,
"ignore_throttled": False
}
def on_settings_load(self):
@@ -303,12 +308,11 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
if "checks" in data:
del data["checks"]
if "check_providers" in data:
del data["check_providers"]
checks = self._get_configured_checks()
if "octoprint" in checks:
data["octoprint_checkout_folder"] = self._get_octoprint_checkout_folder(checks=checks)
data["octoprint_tracked_branch"] = self._get_octoprint_tracked_branch(checks=checks)
data["octoprint_pip_target"] = self._get_octoprint_pip_target(checks=checks)
data["octoprint_type"] = checks["octoprint"].get("type", None)
try:
@@ -339,6 +343,8 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
data["octoprint_type"] = None
data["octoprint_branch_mappings"] = []
data["pip_enable_check"] = "pip" in checks
return data
def on_settings_save(self, data):
@@ -364,6 +370,7 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
)
updated_octoprint_check_config = False
update_pip_check_config = False
if "octoprint_checkout_folder" in data:
self._settings.set(["checks", "octoprint", "checkout_folder"], data["octoprint_checkout_folder"], defaults=defaults, force=True)
@@ -379,11 +386,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
updated_octoprint_check_config = True
elif octoprint_type == "github_commit":
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
self._settings.set(["checks", "octoprint", "method"], "pip", defaults=defaults)
updated_octoprint_check_config = True
elif octoprint_type == "git_commit":
self._settings.set(["checks", "octoprint", "type"], octoprint_type, defaults=defaults)
self._settings.set(["checks", "octoprint", "method"], "update_script", defaults=defaults)
updated_octoprint_check_config = True
if "octoprint_tracked_branch" in data:
self._settings.set(["checks", "octoprint", "branch"], data["octoprint_tracked_branch"], defaults=defaults, force=True)
updated_octoprint_check_config = True
if "octoprint_pip_target" in data:
self._settings.set(["checks", "octoprint", "pip"], data["octoprint_pip_target"], defaults=defaults)
updated_octoprint_check_config = True
if "octoprint_release_channel" in data:
prerelease_branches = self._settings.get(["checks", "octoprint", "prerelease_branches"])
if prerelease_branches and data["octoprint_release_channel"] in [x["branch"] for x in prerelease_branches]:
@@ -395,6 +415,18 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
self._settings.set(["checks", "octoprint", "prerelease_channel"], None, defaults=defaults, force=True)
updated_octoprint_check_config = True
if "pip_enable_check" in data:
checks = self._settings.get(["checks"], merged=True)
if data["pip_enable_check"] in octoprint.settings.valid_boolean_trues:
checks["pip"] = dict(type="pypi_release",
package="pip",
pip="pip=={target_version}")
elif "pip" in checks:
del checks["pip"]
self._settings.set(["checks"], checks, force=True)
self._settings.save()
update_pip_check_config = True
if updated_octoprint_check_config:
self._refresh_configured_checks = True
try:
@@ -403,8 +435,16 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
pass
self._version_cache_dirty = True
if update_pip_check_config:
self._refresh_configured_checks = True
try:
del self._version_cache["pip"]
except KeyError:
pass
self._version_cache_dirty = True
def get_settings_version(self):
return 6
return 7
def on_settings_migrate(self, target, current=None):
@@ -489,6 +529,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
dummy_defaults["plugins"][self._identifier]["checks"]["octoprint"] = None
self._settings.set(["checks", "octoprint"], None, defaults=dummy_defaults)
if current is None or current < 7:
# remove check_providers again
self._settings.set(["check_providers"], None, defaults=dict(check_providers=dict()))
def _clean_settings_check(self, key, data, defaults, delete=None, save=True):
if not data:
# nothing to do
@@ -591,6 +635,12 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
@no_firstrun_access
@Permissions.PLUGIN_SOFTWAREUPDATE_UPDATE.require(403)
def perform_update(self):
throttled = self._get_throttled()
if throttled and isinstance(throttled, dict) and throttled.get("current_issue", False) and not self._settings.get_boolean(["ignore_throttled"]):
# currently throttled, we refuse to run
return flask.make_response("System is currently throttled, refusing to update "
"anything due to possible stability issues", 409)
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
return flask.make_response("Printer is currently printing or paused", 409)
@@ -871,6 +921,10 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
to_be_updated.remove("octoprint")
tmp = ["octoprint"] + to_be_updated
to_be_updated = tmp
if "pip" in to_be_updated:
to_be_updated.remove("pip")
tmp = ["pip"] + to_be_updated
to_be_updated = tmp
updater_thread = threading.Thread(target=self._update_worker, args=(populated_checks, to_be_updated, force))
updater_thread.daemon = False
@@ -1063,25 +1117,28 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
from flask_babel import gettext
if not "type" in check:
raise exceptions.UnknownCheckType()
result = dict(check)
if target == "octoprint":
from flask_babel import gettext
from octoprint.util.version import is_released_octoprint_version, is_stable_octoprint_version
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
displayName = check.get("displayName")
if displayName is None:
# displayName missing or set to None
result["displayName"] = to_unicode(gettext("OctoPrint"), errors="replace")
displayName = gettext("OctoPrint")
result["displayName"] = to_unicode(displayName, errors="replace")
result["displayVersion"] = to_unicode(check.get("displayVersion"), errors="replace")
if result["displayVersion"] is None:
displayVersion = check.get("displayVersion")
if displayVersion is None:
# displayVersion missing or set to None
result["displayVersion"] = "{octoprint_version}"
displayVersion = "{octoprint_version}"
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
stable_branch = "master"
release_branches = []
@@ -1126,6 +1183,23 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
# we force python unequality check for pip installs, to be able to downgrade
result["release_compare"] = "python_unequal"
elif target == "pip":
import pkg_resources
displayName = check.get("displayName")
if displayName is None:
# displayName missing or set to None
displayName = gettext("pip")
result["displayName"] = to_unicode(displayName, errors="replace")
displayVersion = check.get("displayVersion")
if displayVersion is None:
# displayVersion missing or set to None
distribution = pkg_resources.get_distribution("pip")
if distribution:
displayVersion = distribution.version
result["displayVersion"] = to_unicode(displayVersion, errors="replace")
else:
result["displayName"] = to_unicode(check.get("displayName"), errors="replace")
if result["displayName"] is None:
@@ -1230,6 +1304,24 @@ class SoftwareUpdatePlugin(octoprint.plugin.BlueprintPlugin,
return None
def _get_octoprint_tracked_branch(self, checks=None):
if checks is None:
checks = self._get_configured_checks()
if not "octoprint" in checks:
return None
return checks["octoprint"].get("branch")
def _get_octoprint_pip_target(self, checks=None):
if checks is None:
checks = self._get_configured_checks()
if not "octoprint" in checks:
return None
return checks["octoprint"].get("pip")
def _register_custom_events(*args, **kwargs):
return ["update_succeeded", "update_failed"]
@@ -1 +1 @@
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
#settings_plugin_softwareupdate_updatelist{display:block;width:auto;max-height:500px;overflow-x:hidden;overflow-y:scroll;padding-right:2px;margin-bottom:1em}td.settings_plugin_softwareupdate_column_update{width:16px}td.settings_plugin_softwareupdate_column_information .line{display:block}#settings_plugin_softwareupdate_workingdialog_output{font-size:.8em}#settings_plugin_softwareupdate_workingdialog_output .message{font-weight:700}#settings_plugin_softwareupdate_workingdialog_output .separator{font-weight:700;color:#666}#settings_plugin_softwareupdate_workingdialog_output .stdout{color:#333}#settings_plugin_softwareupdate_workingdialog_output .stderr{color:#900}#settings_plugin_softwareupdate_workingdialog_output .call{color:#009}#settings_plugin_softwareupdate_workingdialog_output .message_error{font-weight:700;color:#900}.softwareupdate_notification ul{margin:10px 0 10px 25px}.softwareupdate_notification ul .name{text-overflow:ellipsis;white-space:nowrap;overflow:hidden;display:block}
@@ -6,6 +6,11 @@ $(function() {
self.printerState = parameters[1];
self.settings = parameters[2];
self.access = parameters[3];
// optional
self.piSupport = parameters[4]; // might be null!
self.popup = undefined;
self.updateInProgress = false;
@@ -25,7 +30,8 @@ $(function() {
self.octoprintReleasedVersion = ko.observable();
self.octoprintUnconfigured = ko.pureComputed(function() {
return self.error_checkoutFolder();
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "git_commit"
&& self.error_checkoutFolder();
});
self.octoprintUnreleased = ko.pureComputed(function() {
return self.settings.settings.plugins.softwareupdate.octoprint_type() === "github_release"
@@ -42,9 +48,12 @@ $(function() {
self.config_cacheTtl = ko.observable();
self.config_notifyUsers = ko.observable();
self.config_trackedBranch = ko.observable();
self.config_checkoutFolder = ko.observable();
self.config_pipTarget = ko.observable();
self.config_checkType = ko.observable();
self.config_releaseChannel = ko.observable();
self.config_pipEnableCheck = ko.observable();
self.error_checkoutFolder = ko.pureComputed(function() {
return self.config_checkType() === "git_commit"
@@ -52,11 +61,12 @@ $(function() {
});
self.enableUpdate = ko.pureComputed(function() {
return !self.updateInProgress && self.environmentSupported();
return !self.updateInProgress && self.environmentSupported() && !self.printerState.isPrinting() && !self.throttled();
});
self.enable_configSave = ko.pureComputed(function() {
return self.config_checkType() === "github_release"
|| self.config_checkType() === "github_commit"
|| (self.config_checkType() === "git_commit" && !self.error_checkoutFolder());
});
@@ -92,6 +102,10 @@ $(function() {
return _.filter(self.versions.items(), function(info) { return info.updateAvailable && info.updatePossible; });
});
self.throttled = ko.pureComputed(function() {
return self.piSupport && self.piSupport.currentIssue() && !self.settings.settings.plugins.pluginmanager.ignore_throttled();
});
self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function() {
if (self.loginState.hasPermission(self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK)) {
self.performCheck();
@@ -149,7 +163,10 @@ $(function() {
notify_users: self.config_notifyUsers(),
octoprint_type: self.config_checkType(),
octoprint_release_channel: self.config_releaseChannel(),
octoprint_checkout_folder: self.config_checkoutFolder()
octoprint_checkout_folder: self.config_checkoutFolder(),
octoprint_tracked_branch: self.config_trackedBranch(),
octoprint_pip_target: self.config_pipTarget(),
pip_enable_check: self.config_pipEnableCheck()
}
}
};
@@ -168,7 +185,8 @@ $(function() {
self._copyConfig = function() {
var availableCheckTypes = [{"key": "github_release", "name": gettext("Release")},
{"key": "git_commit", "name": gettext("Commit")}];
{"key": "github_commit", "name": gettext("Github Commit")},
{"key": "git_commit", "name": gettext("Local checkout")}];
self.config_availableCheckTypes(availableCheckTypes);
var availableReleaseChannels = [];
@@ -183,6 +201,10 @@ $(function() {
self.config_checkType(self.settings.settings.plugins.softwareupdate.octoprint_type());
self.config_releaseChannel(self.settings.settings.plugins.softwareupdate.octoprint_release_channel());
self.config_checkoutFolder(self.settings.settings.plugins.softwareupdate.octoprint_checkout_folder());
self.config_trackedBranch(self.settings.settings.plugins.softwareupdate.octoprint_tracked_branch());
self.config_pipTarget(self.settings.settings.plugins.softwareupdate.octoprint_pip_target());
self.config_pipEnableCheck(self.settings.settings.plugins.softwareupdate.pip_enable_check());
};
self._copyConfigBack = function() {
@@ -208,11 +230,11 @@ $(function() {
}
var fullNameTemplate = gettext("%(name)s: %(version)s");
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: value.displayName, version: value.displayVersion});
value.fullNameLocal = _.sprintf(fullNameTemplate, {name: _.escape(value.displayName), version: _.escape(value.displayVersion)});
var fullNameRemoteVars = {name: value.displayName, version: gettext("unknown")};
var fullNameRemoteVars = {name: _.escape(value.displayName), version: gettext("unknown")};
if (value.hasOwnProperty("information") && value.information.hasOwnProperty("remote") && value.information.remote.hasOwnProperty("name")) {
fullNameRemoteVars.version = value.information.remote.name;
fullNameRemoteVars.version = _.escape(value.information.remote.name);
}
value.fullNameRemote = _.sprintf(fullNameTemplate, fullNameRemoteVars);
@@ -476,36 +498,46 @@ $(function() {
type: "error"
});
self._updateClicked = false;
} else {
var html = "<p>" + gettext("This will update the following components and restart the server:") + "</p>";
html += "<ul>";
_.each(items, function(item) {
html += "<li>"
+ "<span class=\"name\" title=\"" + item.fullNameRemote + "\">" + item.fullNameRemote + "</span>";
if (item.releaseNotes) {
html += "<br><a href=\"" + item.releaseNotes + "\" target=\"_blank\" rel=\"noreferrer noopener\">" + gettext("Release Notes") + "</a>"
}
html += "</li>";
});
html += "</ul>";
html += "<p>" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.") + "</p>"
+ "<p><strong>" + gettext("This action may disrupt any ongoing print jobs.") + "</strong></p>"
+ "<p>" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "</p>"
+ "<p>" + gettext("Are you sure you want to proceed?") + "</p>";
showConfirmationDialog({
title: gettext("Are you sure you want to update now?"),
html: html,
proceed: gettext("Proceed"),
onproceed: function() {
self.performUpdate((force === true),
_.map(items, function(info) { return info.key }));
},
onclose: function() {
self._updateClicked = false;
}
});
return;
}
if (self.throttled()) {
self._showPopup({
title: gettext("Can't update while throttled"),
text: gettext("Your system is currently throttled. OctoPrint refuses to run updates while in this state due to possible stability issues."),
type: "error"
});
self._updateClicked = false;
return;
}
var html = "<p>" + gettext("This will update the following components and restart the server:") + "</p>";
html += "<ul>";
_.each(items, function(item) {
html += "<li>"
+ "<span class=\"name\" title=\"" + item.fullNameRemote + "\">" + item.fullNameRemote + "</span>";
if (item.releaseNotes) {
html += "<br><a href=\"" + item.releaseNotes + "\" target=\"_blank\" rel=\"noreferrer noopener\">" + gettext("Release Notes") + "</a>"
}
html += "</li>";
});
html += "</ul>";
html += "<p>" + gettext("Be sure to read through any linked release notes, especially those for OctoPrint since they might contain important information you need to know <strong>before</strong> upgrading.") + "</p>"
+ "<p><strong>" + gettext("This action may disrupt any ongoing print jobs.") + "</strong></p>"
+ "<p>" + gettext("Depending on your printer's controller and general setup, restarting OctoPrint may cause your printer to be reset.") + "</p>"
+ "<p>" + gettext("Are you sure you want to proceed?") + "</p>";
showConfirmationDialog({
title: gettext("Are you sure you want to update now?"),
html: html,
proceed: gettext("Proceed"),
onproceed: function() {
self.performUpdate((force === true),
_.map(items, function(info) { return info.key }));
},
onclose: function() {
self._updateClicked = false;
}
});
};
self._showWorkingDialog = function(title) {
@@ -627,7 +659,7 @@ $(function() {
break;
}
case "updating": {
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: messageData.name, version: messageData.version});
text = _.sprintf(gettext("Now updating %(name)s to %(version)s"), {name: _.escape(messageData.name), version: _.escape(messageData.version)});
self.loglines.push({line: "", stream: "separator"});
self.loglines.push({line: _.repeat("+", text.length), stream: "separator"});
self.loglines.push({line: text, stream: "message"});
@@ -781,7 +813,8 @@ $(function() {
OCTOPRINT_VIEWMODELS.push({
construct: SoftwareUpdateViewModel,
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel"],
dependencies: ["loginStateViewModel", "printerStateViewModel", "settingsViewModel", "accessViewModel", "piSupportViewModel"],
optional: ["piSupportViewModel"],
elements: ["#settings_plugin_softwareupdate", "#softwareupdate_confirmation_dialog", "#wizard_plugin_softwareupdate"]
});
});
@@ -1,7 +1,7 @@
#settings_plugin_softwareupdate_updatelist {
display: block;
width: auto;
height: 500px;
max-height: 500px;
overflow-x: hidden;
overflow-y: scroll;
padding-right: 2px;
@@ -0,0 +1,8 @@
<div class="control-group">
<div class="controls">
<label class="checkbox">
<input type="checkbox" data-bind="checked: config_pipEnableCheck"> {{ _('Enable <code>pip</code> update checks') }}
<span class="help-block">{{ _('If you check this, OctoPrint will also notify you of updates of the <code>pip</code> tool used by OctoPrint to install plugins and updates and allow you to update it through OctoPrint. <code>pip</code> is outside of the control of the OctoPrint maintainer, so enable at your own risk.') }}</span>
</label>
</div>
</div>
@@ -0,0 +1,7 @@
<div class="control-group" data-bind="visible: config_checkType() === 'github_release' || config_checkType() === 'github_commit'">
<label class="control-label">{{ _('OctoPrint <code>pip</code> target') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: config_pipTarget">
<span class="help-block">{{ _('You should normally not have to change this.') }}</span>
</div>
</div>
Loaded 100 of 237 files, more files were not shown because too many files have changed in this diff. Show more